一次为所有单元测试初始化​​私有字段

时间:2018-06-24 04:12:39

标签: c# unit-testing

无论如何,对于同一单元中的所有单元测试,我都可以一次初始化本地变量吗?

如果我使用[TestInitialize()],则每个单元测试都会发生一次初始化,类似地,如果我使用构造函数,则每个测试都将被初始化一次。

我曾考虑使用[ClassInitialize()],但是此方法必须是静态的,并且不能访问私有字段。

[TestClass()]
public sealed class ElasticsearchTest
{
    private ElasticsearchClient _elasticClient;

    [ClassInitialize()]
    public static void ClassInit()
    {
        // cannot do this... visual studio error: 
        // An object reference is required for the non-static field, method or property
        _elasticClient = new ElasticsearchClient("http://localhost:9200", true);
    }

    [TestInitialize()]
    public void TestInit()
    {
        // this initialization happens once for each test
        _elasticClient = new ElasticsearchClient("http://localhost:9200", true);
    }

    [TestMethod()]
    public void Test1()
    {
        var res = _elasticClient.SearchDocuments("table");
    }

    [TestMethod()]
    public void Test2()
    {
        var res = _elasticClient.SearchDocuments("chair");

    }
}

1 个答案:

答案 0 :(得分:2)

基于MS测试的标准解决方案是使用[ClassInitialize]。如果这样做,则还需要将private变量更改为static

private static ElasticsearchClient _elasticClient;

或者,考虑使用(而不是[ClassInitialize]):

private static ElasticsearchClient _elasticClient = new ElasticsearchClient("http://localhost:9200", true);