2016-04-03 3 views
0

Ich bin in einer Situation, wo ich Komponententestfälle schreibe, um den Code zu testen, und ich bin auf eine Situation gestoßen, in der ich das Objekt für PrivateObject sowie PrivateType nicht erstellen kann. Ich habe viel gesucht, aber nichts gefunden. Schließlich Frage stellen, um Hilfe zu suchen. Ich verwende MSFakes-Tests.C# Reflection - Wie erstellt man ein PrivateObject-Objekt oder ein PrivateType-Objekt, wenn die Klasse keinen Standardkonstruktor hat?

Unten ist mein Beispielcode:

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 
    } 

} 

Jetzt habe ich beide Verfahren testen möchten.

Wenn ich unten Code schreiben, ich bin unten Fehler während der Laufzeit nicht immer Zeit kompilieren:

[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. 

Das Gleiche gilt für Private geschieht auch. Also, wie kann ich ein Objekt erstellen, wenn die Klasse keinen Standardkonstruktor hat? Vielen Dank im Voraus.

Antwort

0

PrivateObject Konstruktor akzeptieren Variable Anzahl der Argumente, die an Type Konstruktor übergeben werden. See documentation

PrivateObject obj = new PrivateObject(typeof(A), 1); 

Sie können auch pass initialized object zu PrivateObject.

PrivateObject obj = new PrivateObject(new A(1)); 
+0

Schätzen Sie Ihre Bemühungen Umer. Danke –

+0

@amargadekar funktioniert das für dich? –

+0

hi @downvoter was ist los mit der Antwort? –

Verwandte Themen