I'm using xUnit to unit test my application and am currently setting up a test to use the [Theory]
attribute to test several different data inputs.
In order to do so I need to create test data in my previously mocked data context. This works, but when I add the data in the test itself each run ends up with the same data being added again.
My current test:
[Theory]
[InlineData(null, 2)]
[InlineData("en-AU", 1)]
public void Test1(string term, int expectedCount)
{
Fixture.DbContext.Culture.Add(new Culture { Name = "English (Australia)", CultureCode = "en-AU", NativeName = "English (Australia)"});
Fixture.DbContext.Culture.Add(new Culture { Name = "English (United States)", CultureCode = "en-US", NativeName = "English (United States)" });
Fixture.DbContext.Culture.Add(new Culture { Name = "English", CultureCode = "en", NativeName = "English", NeutralCultureFlag = true });
var result = controller.GetRegions(term);
Assert.IsType(typeof (JsonResult), result);
var jsonResult = (JsonResult)result;
Assert.Equal(expectedCount, jsonResult.Data);
}
Is there a way of only setting up the test data once for each run of InlineData
? I know I could put it in the constructor of the test class but I would prefer not to do this as this seems unnecessary if this is the only test in the class that uses that data.
Is there a way of only setting up the test data once for each run of InlineData? ...if this is the only test in the class that uses that data.
If I am understanding the situation correctly, I believe what is sought is to use XUnit's Class Fixture (using IClassFixture<>
implemented on the test class) which can provide the logic of a single test context shared amongst the test(s) for a single class where needed. Then cleaned up when all of those local tests are done.
Otherwise if the thought is re-use, one can use a Collection Fixture when one test context is to be created once and then shared amongst many different test classes and once all is done, it will then be cleaned up.
But you mentioned that one can use the constructor/dispose and that will create and destroy a new context for each test on that class; which as you mentioned is a waste when only one test uses it.
So you have two other options which can provide a way to not pay the overhead of creating and destroying the context uncessarily.
Reference
Final Thoughts
Frankly if this is such a unique test, why does it have to be with a set of theories? Simply make it an individual test.
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