views:

250

answers:

2

Using Visual Studio generate Test Unit class. Then comment in, the class initialization method. Inside it add your property, using the testContext argument.

Upon test app startup this method is indeed called by the testing infrastructure.

//Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
    /*
     * Any user defined testContext.Properties
     * added here will be erased after this method exits
     */
   testContext.Properties.Add("key", 1 ) ; // place the break point here
}

After leaving MyClassInitialize, any properties added by user are lost. Only the 10 "official" ones are left.

Actually TestContext gets overwritten, with the inital offical one, each time before each test method is called. It it not overwritten only if user has test initialization method, the changes made over there are passed to the test.

//Use TestInitialize to run code before running each test
[TestInitialize()]public void MyTestInitialize(){ 
     this.TestContext.Properties.Add("this is preserved",1) ;
}

This effectively means TestContext.Properties is "mostly" read only, for users. Which is not clearly documented in MSDN.

It seems to me this is very messy design+implementation. Why having TestContext.Properties as an collection, at all ? Users can do many other solutions to have class wide initialization.

Please discuss.

--DBJ


A: 

I believe you have to persist a copy of the testContext or it will drop out of scope.

I added:

private TestContext _tc;

and added to the Initialize

tc = testContext;

When I look at tc from one of the tests it contains the newly added property.

Cheddar
This will not work in the context of a Test Unit class generated by Visual Studio. One very obvious reson is that initialization method in my initial post is static. As generated by Visual Studio.
DBJDBJ
A: 

The TestContext is unique for each test so initializing it in the ClassInitialize will not work. You should only use it for TestInitialize, TestCleanup and TestMethod methods.

This post does a good job of explaining how the tests from one class are run including threading.

That being said, I have not found a use yet for the TestContext but I am new to MSTest. I agree the MSDN documentation is confusing. Having all of the sample methods write to the console or throw up a message box does nothing to represent the possibilities.

Maggie
@Maggie, agreed, but ... the point I am making is that (worse) implementation is confusing because (much worse) it is based on a desing which is confused. The outcome is the bug, which is being sold as a "feature".
DBJDBJ