Sunday, June 8, 2008

How NOT to write a Unit Test

Discussion by Roy Osherove of Typemock
View in the Blog: Iserializable.com

Open discussions from the group:

• Unit testing for Data Access
• Link to existing code (Legacy)
• Duplication between Unit Tests and function tests
• Other platforms or older languages
• Unit testing after refactoring
• Interface Testing
• Can you write unit tests w/ only what Visual Studio provides

Book: The Art of Unit Testing
http://The.ArtOfUnitTesting.com

Unit Testing should be a test of small functional pieces of code

What’s assumed is that it will make it easier to find bugs, which is not necessarily true because there can be errors in the text, it should make things easier to maintain (perhaps if you refactor your tests), and it will make it easier to understand the code, which may not necessarily be true if you’re not testing for the right things. However, if the prior three are correct, it should make it easier to develop.

Testing with a real world agenda:
• Make test trustworthy so that testers will run the tests
• Make sure you are testing the right things
• Make the test fail first, then work on making it pass (make it fail when it should, and pass when it should)

Assuring code coverage—that you have created testing in all the necessary areas.

Avoid testing logic
• No Ifs, SWITCHs, or CASEs
• Only create, configure, act and assert
• Test logic = test bugs (don’t repeat the same algorithm in your test as you use in the app because the app logic may have a bug)
• State-based testing
• Make tests easy to run—try to make all the tests run from the click of one button
• Create maintainable tests--test only public APIs (testing private makes the test brittle)
• Reuse test code as much as possible, don’t write a new test for each piece of logic

File Structure—for each project create a test project with the same name and add a suffix like “_Test”. You may want to create a test file for each class in the project.

Avoid multiple Asserts
Don’t over specify
Avoic Mocks if you can, although, you have to do it sometimes in order to return something back into the calling class

Another good book: Working Effectively with Legacy Code – Michael Feathers

Tools: ReSharper Tool, Rinomox

1 comment:

Janus said...

I would like to hear more about this at some point. I realize that we are in the process of implementing Unit Testing on our apps. I think it will be helpful for everyone (Dev, QA, and PMs) to understand exactly what unit tests will cover and what they won't cover in our apps, using one of our apps as an actual example.

- Janus