When I run all tests, the method decorated with [TestInitialize]
attribute, gets executed for every test method I have.
The tests are of type integration test, to test database access logic. And in the method with [TestInitialize]
attribute, I insert some test data into the database which causes the following exception when executed more than once:
Result Message: Initialization method ......FilterRepositoryTests.Initialize threw exception. System.Data.Entity.Infrastructure.DbUpdateException: System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.User' with unique index 'IX_Name'. The duplicate key value is (Person 1). The statement has been terminated..
Inserting the data takes some time, so I rather not delete and recreate the database for every test method I have.
So how can I execute an initialization/setup method only once for all test?
You can use ClassInitialize attribute which will be invoked once for all the test methods in that class.
Once done with the tests, you may need to cleanup with ClassCleanup attribute.
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