做集成测试时如何让visual studio 运行 TestInitialize一次?

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

当我 运行 所有测试时,用 [TestInitialize] 属性修饰的方法会针对我拥有的每个测试方法执行。

测试类型为集成测试,用于测试数据库访问逻辑。在具有 [TestInitialize] 属性的方法中,我将一些测试数据插入数据库,这在多次执行时会导致以下异常:

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

插入数据需要一些时间,所以我宁愿不为我拥有的每种测试方法删除并重新创建数据库。

那么如何才能对所有测试只执行一次 initialization/setup 方法?

您可以使用 ClassInitialize 属性,该属性将为 class 中的所有测试方法调用一次。

完成测试后,您可能需要使用 ClassCleanup 属性进行清理。