Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make visual studio run TestInitialize once when doing integration test?

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?

like image 239
Quoter Avatar asked Mar 17 '23 00:03

Quoter


1 Answers

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.

like image 50
Sriram Sakthivel Avatar answered Apr 08 '23 22:04

Sriram Sakthivel