2

Is there anyway that I could initialize my local variable once, for all unit tests, in the same class?

If I used [TestInitialize()], the initialization happens once for each unit test, similarly if I use a constructor, it will be called once per test.

I thought of using [ClassInitialize()], but this method has to be static and cannot access private fields.

[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");

    }
}
Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137
  • 1
    Possible duplicate of [TestInitialize vs ClassInitialize](https://stackoverflow.com/questions/22999816/testinitialize-vs-classinitialize) – mjwills Jun 24 '18 at 04:38

1 Answers1

3

The standard MS Test based solution to this problem is to use [ClassInitialize]. If you do this, you will also need to change the private variable to be static:

private static ElasticsearchClient _elasticClient;

Alternatively, consider using (instead of [ClassInitialize]):

private static ElasticsearchClient _elasticClient = new ElasticsearchClient("http://localhost:9200", true);
mjwills
  • 23,389
  • 6
  • 40
  • 63