I’m using NUnit and Rhino Mocks. I use the AAA-syntax and I do the Arrange and Act in the setup method, and every Test method is an 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
}
As you might expect, the code in SomeMethod() throws an exception (as expected), wich makes every test fail (unwanted). I workaround this by doing
try
{
// Act
subject.SomeMethod("Invalid Input");
}
catch(Exception ex)
{
// Swallow, this exception is expected.
}
But that is just ugly.
What I would like to be able to do is
[SetUp]
[ExpectedException] // <-- this works for Test methods, but not for SetUp methods
public void Setup()
{
// etc...
}
but I can’t find anything like it.
Do you know of anything?
I don’t think using an attribute like
ExpectedExceptionis a good idea.SetUpis to prepare something for the test methods, it shouldn’t throw exception.If it must throw, and you want to limit the code line number. Then put them into one line like below: