![](/img/trans.png)
[英]Reflection C#: Create instance of an object which has no default constructor
[英]C# Reflection - How to create PrivateObject object or PrivateType object if class does not have default constructor?
我在编写单元测试用例以测试代码的情况下,遇到了无法为PrivateObject和PrivateType创建对象的情况。 我搜索了很多,但没有发现任何帮助。 最后提出问题寻求帮助。 我正在使用MSFakes测试。
下面是我的示例代码:
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
}
}
现在,我想测试这两种方法。
如果我写下面的代码,我将在运行时而不是编译时遇到错误:
[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.
同样,PrivateType也是如此。 那么,如果类没有默认构造函数,该如何创建对象呢? 提前致谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.