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
TestSetupand 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.