简体   繁体   English

Visual Studio单元测试:在每次测试之前运行初始化代码

[英]Visual Studio Unit tests: run initialization code before each test

I'm using Visual Studio's Test Tools for unit testing. 我正在使用Visual Studio的测试工具进行单元测试。 I need some initialization code to run before each test . 我需要一些初始化代码才能在每次测试之前运行。

I have a Setup class for the initialization code. 我有一个初始化代码的Setup类。 I already added code to run before each test run , using [AssemblyInitialize] , but I can't figure out how to do the same on a single test basis. 我已经添加的代码每次测试运行之前运行,使用[AssemblyInitialize]但我无法弄清楚如何做同样一个测试的基础上。

I tried using the [TestInitialize] attribute, but this only applies to tests in the same file as the [TestInitialize] method. 我尝试使用[TestInitialize]属性,但这仅适用于与[TestInitialize]方法相同的文件中的测试。 I would like the initialization code to run automatically for all tests in the assembly, without having to explicitly call it in each and every test file. 我希望初始化代码能够自动运行程序集中的所有测试,而不必在每个测试文件中显式调用它。

[TestClass]
public class Setup
{
    [AssemblyInitialize]
    public static void InitializeTestRun(TestContext context)
    {
        //... code that runs before each test run
    }

    [TestInitialize] //this doesn't work!
    public static void InitializeTest()
    {
        //... code that runs before each test
    }
}

The following should work (at least it works with other test frameworks): 以下应该有效(至少它适用于其他测试框架):

  • Create a base class DatabaseIntegrationTests with the TestInitialize method 使用TestInitialize方法创建基类DatabaseIntegrationTests
  • Derive your other Testclasses from that base class 从该基类派生您的其他Testclasses

It is [TestInitialize] but you have the syntax wrong, it doesn't take a context: [TestInitialize]但你的语法错误,它没有上下文:

[TestInitialize]
public static void InitializeTests()
{
    //... code that runs before each test
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM