SweatCoder SweatCoder - 1 year ago 127
C# Question

Is there a non-static ClassInitialize alternative in MSTest?

I'm using Visual Studio 2012 test framework (I guess that's MSTest). I have some code that I need to run once and only once before the various testmethods run. ClassInitialize seemed perfect until I learned that it must be static.

First, I have an instance variable for ChromeDriver:

private ChromeDriver driver;

I think I need to have something like this, but nonstatic:

public static void Initialize() {
ChromeOptions options = new ChromeOptions();
options.LeaveBrowserRunning = true;
driver = new ChromeDriver(@"C:\MyStuff", options);

The above does not compile because class instances are being newed up inside this static method. But I'm forced to make it static, or runtime errors result saying "this has to be a static method" and "wrong signature", etc.

If I spin up my ChromeDriver (declared as a class variable) either in the class constructor or in a TestInitialize method, everything works fine BUT a new browser window opens for each and every test. So when I have 50 test methods I'm going to have 50 instances of Chrome opened, and that's bad.

I just want to reuse my
instance for every test and not have to spin up a new one each time, which opens a new browser.

How can this be done?

Answer Source

I'm not sure whether it's really the best approach, but you could make it a static variable - it's fine to access static variables from instance methods (your tests) after all.

Note that this could cause problems if you try to run your tests in parallel, however. It's probably worth investigating what the test instance lifecycle is - where you can use one instance for multiple tests, in which case initializing the instance variable in the constructor might be another reasonable approach.

(Unless it actually takes a long time to initialize the driver, I'd be tempted to create it on a per-test basis anyway...)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download