Pages

Tuesday 12 January 2010

Setup, TearDown, When to Mock?

 

I’m writing this while eating at the Launceston Place, a very comfy restaurant near Gloucester Road. Warm decor, soft lighting and excellent service.

  • Setup and TearDown

Only use those to respectively initialise then destroy mock objects. Methods with [Setup] and [TearDown] attributes are called before and after each test so they’re the only methods that guaranty that things get cleaned up.

Best to avoid the [SetupFixture] attribute (to mark a class that contains Setup and Teardown methods called just once before ALL tests), as well as [TestFixtureSetup]/[TestFixtureTeardown] (called once only before all tests in a fixture). I tried to be clever and used them and ended up having to debug nasty side effects. Unit tests are supposed to run in isolation, so just one [Setup] before and one [TearDown] after each of them, that’s it.

  • What should be mocked?

Yesterday while writing a UT I bumped into this question: should I bother writing a mock for that object or can’t I just use the real thing?

One answer: objects that access external systems (DB, hard-drive, client API to some server-based system, …) should always be mocked (for unit-tests that is, not integration tests), otherwise the test is not repeatable, and it’s slow…

If a method under test accesses an injected object and this object does only in-memory stuff, then no need to mock it. It would make sense to mock it because after all this injected object is not actually the thing you want to test… Still, the more real objects are covered by the test, the better. As long as they all run in-memory and do not prevent the test from being repeatable, all is well. So no need to waste time writing a mock in that case.

No comments: