我正处于编写单元测试用例来测试代码的情况,我遇到过一种情况,我无法为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也是如此。 那么如果类没有默认构造函数,我怎么能创建对象呢? 提前谢谢。
答案 0 :(得分:0)
PrivateObject
构造函数接受将传递给Type
构造函数的可变数量的参数。 See documentation
PrivateObject obj = new PrivateObject(typeof(A), 1);
您还可以pass initialized object到PrivateObject
。
PrivateObject obj = new PrivateObject(new A(1));