【发布时间】:2010-11-19 08:44:52
【问题描述】:
我正在使用 NUnit 和 Rhino Mocks。我使用 AAA 语法,并在 setup 方法中执行 Arrange 和 Act,每个 Test 方法都是一个 Assert。
[TestFixture]
public class When_subSystem_throws_exception
{
SomeClass subject; // System under test
[SetUp]
public void Setup()
{
// Arrange
IDependency dependency = MockRepository.GenerateStub<IDependency>();
dependency.Stub(m => m.DoStuff()).Throw(new Exception()); // This method is called from within SomeMethod()
subject = new SomeClass(dependency);
// Act
subject.SomeMethod("Invalid Input");
}
// Assert
[Test]
public void should_log_an_exception_to_the_logger()
{
// Do stuff to verify that an exception has been logged
}
// More tests
}
如您所料,SomeMethod() 中的代码会抛出异常(如预期的那样),这会使每个测试都失败(不需要)。我通过这样做来解决这个问题
try
{
// Act
subject.SomeMethod("Invalid Input");
}
catch(Exception ex)
{
// Swallow, this exception is expected.
}
但这太丑了。
我想做的是
[SetUp]
[ExpectedException] // <-- this works for Test methods, but not for SetUp methods
public void Setup()
{
// etc...
}
但我找不到类似的东西。
你知道什么吗?
【问题讨论】:
标签: c# unit-testing nunit