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