NUnit 使用备用构造函数执行
我有一个包含一些单元测试的类,但是当我运行测试时,我希望使用不同的构造函数创建该类。像这样的事情:
[TestFixture]
public class MyClass
{
public MyClass() { /* set up for production */ }
[TestFixtureConstructor]
public MyClass() { /* set up for testing */ }
[Test]
public void FirstTest()
{
// assert some values
}
}
这可能吗?
我考虑过使用静态工厂方法在生产中创建类(使用私有构造函数),并使用公共构造函数用于测试框架。
有人还有其他解决方案吗?
I have a class which has some unit tests, but when I am running tests I would like the class to be created with a different constructor. Something like this:
[TestFixture]
public class MyClass
{
public MyClass() { /* set up for production */ }
[TestFixtureConstructor]
public MyClass() { /* set up for testing */ }
[Test]
public void FirstTest()
{
// assert some values
}
}
Is this even possible?
I have considered using a static factory method for creating the class in production (with a private constructor), and a public constructor for the testing framework.
Does anyone have any other solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不这样做。
您没有在实际代码中使用的类内部编写测试;您在类外部编写测试。我相信大多数测试套件都有“Teardown”的概念以及相反的概念;为给定的执行设置测试环境。
You don't do this.
You do not have your tests written inside the class that you use in real code; you write your tests external to the classes. I believe most testing suites have the concept of 'Teardown' and the opposite; to set up the test environment for a given execution.
举一个 Silky 正确方法的简单例子:
To give a quick example of silky's correct approach:
如果您真的真的想要这个,您可以看看
TestFixtureSetUp
。介绍如下:
该属性在 TestFixture 内部使用,以提供一组在执行装置中的任何测试之前执行一次的函数。一个 TestFixture 只能有一个 TestFixtureSetUp 方法。如果定义了多个,TestFixture 将成功编译,但其测试将不会运行。
示例:
但是您应该小心使用它,否则它会失败 单元测试的目的。
If you really really want this you can take a look at
TestFixtureSetUp
.Here's the introduction:
This attribute is used inside a TestFixture to provide a single set of functions that are performed once prior to executing any of the tests in the fixture. A TestFixture can have only one TestFixtureSetUp method. If more than one is defined the TestFixture will compile successfully but its tests will not run.
Example:
But you should use this with care, or else it defeats the purpose of unit test.