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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With