简体   繁体   English

NUnit SetUp中的ExpectedException

[英]ExpectedException in NUnit SetUp

I'm using NUnit and Rhino Mocks. 我正在使用NUnit和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. 我使用AAA语法,并在设置方法中执行“安排”和“操作”,并且每个“测试”方法都是“断言”。

[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). 如您所料,SomeMethod()中的代码将引发异常(如预期),这会使每个测试失败(不需要)。 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? 你知道什么吗

It doesn't work in Setup for a reason, not because of NUnit's bug. 它不能在安装程序中运行是有原因的,不是因为NUnit的错误。

It's a very bad practice for a unit-test to have exception throwing inside the SetUp method. 对于单元测试来说,在SetUp方法中引发异常是非常糟糕的做法。 If you are testing a particular scenario where a exception is the expected result, it should be done inside a [Test] method. 如果要测试特定的情况,其中例外是预期的结果,则应在[Test]方法内完成。 You should rearrange your code subsequently. 您应该随后重新排列代码。

I don't think using an attribute like ExpectedException is a good idea. 我不认为使用ExpectedException类的属性是个好主意。 SetUp is to prepare something for the test methods, it shouldn't throw exception. SetUp是为测试方法做准备的东西,它不应引发异常。 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 { }

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) - ie common or repeated "arrange" steps. 该设置用于设置测试的前提条件和通用对象,即通用或重复的“安排”步骤。

Each test method should "act" and "assert" individually (and may also need additional "arrange" steps specific to the test). 每种测试方法都应分别“起作用”和“声明”(并且可能还需要针对测试的其他“安排”步骤)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM