在 NUnit 中测试不可编译的代码
我有一个类,现在应该始终在其有效之前填充某个成员。为了强制执行这一点,该类没有默认构造函数,而是有一个接受该必需成员的值的构造函数。设置与下面类似:
public class MyClass
{
public string Owner { get; protected set; }
public MyClass(string owner)
{
this.Owner = owner;
}
}
现在我想编写一个测试来确保实际上没有默认构造函数,这样如果将来添加了默认构造函数,我们就会想起没有默认构造函数的原因,并且是被迫考虑这样做的影响。尽管如此,显然尝试在测试中调用默认构造函数不仅会失败,而且不会编译。
有没有一种好方法可以在不修改我原来的类的情况下完成这种测试?如果没有,我想我可以实现一个抛出异常的默认构造函数。我唯一犹豫的是,调用默认构造函数现在成为可编译代码,然后我们必须依赖其他测试来确保不会编写此类代码。
想法?
I have a class which for now should always have a certain member populated before it is valid. To enforce this, the class has no default constructor and instead has a constructor which accepts a value for that required member. The setup is similar to this below:
public class MyClass
{
public string Owner { get; protected set; }
public MyClass(string owner)
{
this.Owner = owner;
}
}
Now I'd like to write a test to ensure that there is in fact no default constructor, so that if one gets added in the future, we are reminded of the reasons behind not having one and are forced to consider the impact of doing so. Although, obviously attempting to call the default constructor in a test won't just fail, it won't compile.
Is there a good way to pull off this kind of test without modifying my original class? If not, I suppose I could implement a default constructor which throws an exception. My only hesitation there is that calling the default constructor now becomes compilable code and then we must rely on other tests to ensure such code doesn't get written.
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以调用
Activator.CreateInstance(typeof(MyClass))
尝试运行默认构造函数,并断言抛出MissingMethodException
。You could call
Activator.CreateInstance(typeof(MyClass))
to try to run the default constructor, and assert that aMissingMethodException
is thrown.我将创建一个默认构造函数,将其标记为私有并将您的文档放在那里。那么你这样做的理由就不会被隐藏在某个地方。您必须意识到您将放弃一些需要无参数构造函数的序列化功能。
I would create a default constructor, mark it private and put your documentation there. Then your reasons for doing it won't be hidden off somewhere. You have to realize you'll be giving up some serialization functionality that requires the parameterless constructor.
查看有关动态调用构造函数的页面。
Check out this page on dynamically invoking constructors.
您可以使用反射来检查该类是否有无参数构造函数,如果有则测试失败
you could use reflection to check if there is a no arg constructor for the class and fail the test if there is
是的。一个好方法是使用反射在 try/catch 中尝试无参数构造函数。
Yep. A good way would be to use reflection to try a parameterless constructor within a try/catch.