Friday, 10 November 2006

Tech Ed - Unit Testing Best Practices with VSTS 2005

Went to a lecture by Mark Seeman (who is a senior MS Consultant) about Unit Testing with VSTS. This was a good lecture as an introduction to unit testing as a concept as well as what VSTS gives us out of the box.

He started off by giving his opinion of a unit being a whole assembly, so he believes that we should be thinking of testing an assembly as a whole, but always abstract away from any volatile dependencies such as other changing components or db. Interestingly he was very adamant that we only test the public interface of the component. After explaining his reasons it really gave me a much better picture of what exactly the aim of the game is :). We are really setting out to test the component from a black box aspect and test the contract.

I really liked the agile type testing that he demoed where you create a test and then build the code to meet it, this really gives you a clear sense of a goal and will keep you from going off on a tangent :)

With VSTS he showed us how we can create a test project (and he recommends a test project for each component you test) and then create test methods within this which form our actual tests. We use a declarative TestMethod attribute to the methods to let VS know that the method is a test. Within the methods we can use the assert object to test the results of calls etc. by comparing our expected result with the actual result. When we build up our tests and run them we can use the test manager to check our results and the code coverage tool to see how much of our code we have tested.

He mentioned the following best practices:

  • Always keep tests simple.
  • Always aim to test all your code by aiming for code coverage of around 90%.
  • All logic should be in components so they can be tested, don’t put any login in the UI.
  • Test cases must be independent (should setup and clean down tests)
  • Test cases must be deterministic (you should not do things like create random values)
  • Reproduce bugs as test cases
  • Place tests in separate projects
  • Have a test project per test target
  • Use source control on test projects

No comments: