开发者

NUnit keeping static data across tests

I have a static class that I'm using to hold my test data. When I reference this in my NUnit tests, any changes I开发者_开发百科 make are persisted across tests.

For example, I have this code in my test:

OrderDto orderDto = SampleData.OrderDto;
OrderDetailDto orderDetailDto = SampleData.OrderDetailDto;
orderDto.OrderDetails.Add(orderDetailDto);

And sample data is something like this:

public static class SampleData {
    public static OrderDto OrderDto = new OrderDto { LastName = "Smith", CreatedById = 5, CreatedByDisplayName = "Smith2" };
}

The first time I run it, orderDto has 0 OrderDetails. The second time it has 1, then 2, etc. I thought between NUnit tests, nothing was persisted. Does it cache static properties?


It is up to you to make sure the data is not persisted across unit tests. When executed, a unit test assembly behaves just like a normal assembly, so any statics you initialize stay that way for the duration of the test.

Most unit test frameworks provide a way to inititalise and clean up your state before and after test. In NUnit, the way to do that is to have a method with [SetUp] attribute. This method gets executed before each test.

The easiest way to achieve what I think you want to achieve is to initialise a member field in TestSetup and use that between different tests. Note that we don't use a static member here, which means we don't have to clean it up after the test.

[TestFixture]
public class MyTests {

  OrderDto OrderDto;
  OrderDetailDto;
  [SetUp]
  public void Setup() {
    _OrderDto = new OrderDto { LastName = "Smith", CreatedById = 5, CreatedByDisplayName = "Smith2" };
    _OrderDetailDto = new OrderDetailDto {/*Sample data*/};
  }

  [Test]
  public void TestOrderDetailIsAddedToOrder() {
    orderDto.OrderDetails.Add(_OrderDetailDto);
  }
}


Tests should be isolated, but that doesn't mean they are automatically.

NUnit will run a method of the TestFixture tagged with [SetUp] before each test and [TearDown] afterwards. You can use this and the other NUnit attributes to set up your fixture.


I think I answered my own question with a bit more fiddling. Still not sure why it was updating the object, but if I change the static class to this, it works:

public static class SampleData {
    public static OrderDto OrderDto {
        get { return new OrderDto { LastName = "Smith", CreatedById = 5, CreatedByDisplayName = "Smith2" }; }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜