samedi 2 avril 2016

C# Reflection - How to create PrivateObject object or PrivateType object if class does not have default constructor?

I'm in a situation where I'm writing unit test cases to test the code and i have come across a situation where I'm unable to create the object for PrivateObject as well as PrivateType. I searched a lot but nothing found helful. Finally asking question to seek help. I'm using MSFakes testing.

Below is my sample code:

public class A
{
    //this class is not having default constructor and I can't modify the code as well.
    public A(int id){
    //some code
    }

    private void MethodPrivateA(int id){
       //some code
    }


    private static void MethodPrivateStaticB(int id){
       //some code
    }

}

Now I want to test both of the methods.

If I write below code I'm getting below error at run time not compile time:

[TestClass]
Class TestA
{
    [TestMethod]
    public void CheckMethodATest()
    {

     //my some arrange data

     //here I'm stuck to invoke the method as object is not created
     PrivateObject obj = new PrivateObject(typeof(A)); //here at runtime throws error it does not found default constructor for the class A 
     obj.Invoke("MethodPrivateA", new Object[1]{1});
    }
    //my some assertion code
}

//Please ignore any typo error in the code in case if they exists as I have written code directly over here. It is more conceptual one.

Same happens for PrivateType as well. So how can I create object if class does not have default constructor? Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire