4 c# constructor nunit unit-testing private
如果构造函数是私有的(.NET),如何设置单元测试?
这是我的班级:
public class Class2
{
// Private constructor.
private Class2()
{
}
public static Class2 getInstance()
{
if (x == null)
{
x= new Class2();
}
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试:
[TestFixture]
public class Class2Tester
{
private Class2 test;
[SetUp()]
public void SetUp()
{
// I cant do this. How should I setup this up?
test = new Class2();
}
}
Run Code Online (Sandbox Code Playgroud)
答案是:你没有.不是因为你不能,而是因为你不应该.
通过使构造函数成为私有,您说它的行为不是该类的公共API的一部分.在这种情况下,它的行为要么a)不影响类的公共API,这意味着它不需要进行测试.b)更有可能影响该类的公共API,在这种情况下,围绕该公共API而不是黑盒构造函数编写测试.