开发者

Are TestContext.Properties usable?

开发者 https://www.devze.com 2022-12-25 03:07 出处:网络
Using Visual Studio generate Test Unit class. Then comment in, the class initialization method. Inside it add your property, using the testContext argument.

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.


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.


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.


The TestContext is used to pass information into your tests from outside. Through the test executor or a .runsettings file so its generally data going one way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号