dvdvorle
dvdvorle

Reputation: 961

ExpectedException in NUnit SetUp

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?

Upvotes: 1

Views: 1206

Answers (3)

Jason Li
Jason Li

Reputation: 1585

I don't think using an attribute like ExpectedException is a good idea. SetUp is 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:

try { subject.SomeMethod("Invalid Input"); }catch { }

Upvotes: 2

Paolo
Paolo

Reputation: 22646

Your "act" step should be in the test method not the setup.

The setup is for setting up pre-requisite conditions and common objects for the test(s) - i.e. common or repeated "arrange" steps.

Each test method should "act" and "assert" individually (and may also need additional "arrange" steps specific to the test).

Upvotes: 1

Simone
Simone

Reputation: 11797

It doesn't work in Setup for a reason, not because of NUnit's bug.

It's a very bad practice for a unit-test to have exception throwing inside the SetUp method. If you are testing a particular scenario where a exception is the expected result, it should be done inside a [Test] method. You should rearrange your code subsequently.

Upvotes: 2

Related Questions