NUnit keeping static data across tests

10,031

Solution 1

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);
  }
}

Solution 2

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.

Share:
10,031
Jamie
Author by

Jamie

Freelance developer of mostly web, mostly .net stuff, but there are very few areas I haven't ventured.

Updated on July 11, 2022

Comments

  • Jamie
    Jamie almost 2 years

    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?

  • TrueWill
    TrueWill almost 13 years
    It was updating the static object because there was one instance and that's what your tests did. Unit tests are just like normal code; if they update a static field then the field gets updated. Now you're returning a new instance each time this method is called, which means that changes only affect the current instance.