Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

On the Seventh Day, the Mighty Being Created the 7th Instance

0.00/5 (No votes)
21 Jul 2011CPOL1 min read 5.7K  
Should the test framework create a separate instance of the test class for each test method?

This post was triggered by a recent twitversation which sounded like one of those that people are never tired to argue about. You know, like the sproc one. Granted, on this one, we weren't fighting, just carefully examining the opponent's reasons.

The question is, Should the test framework create a separate instance of the test class for each test method?

One valid point, and that goes back to 2004, is that you could "spoil" the instance in a test method, thus making the next test run in a different context. As a result, the output depends on the order the tests are being run in, and essentially becomes unpredictable.

The solution to this "problem" is simple: just don't modify anything in your test methods! Use Tests for testing, and FixtureSetup for, well, setup. This is a natural distinction between commands (setup/teardown) and queries (tests). This is, incidentally, still another reason for using the Testcase Class per Fixture pattern: put all tests that have the common Arrange-Act code into the same test class, put the above mentioned code into the FixtureSetup method, and just use Asserts in your test methods.

If you absolutely want/have to use a framework that creates an instance per test method (like MsTest or xUnit.net), just put your setup in the constructor.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)