views:

274

answers:

4

How do you decide what to choose:

  1. use mock objects for a test OR
  2. create a test object/ object graph using an IoC framework and run test on that data
+1  A: 

I am very happy with using IoC for much of my app, and especially I appreciate that test-datasources can be injected for testing.

For more problematic backend connections (currently a single ESB call) or functions that need complicated state I mock.

anders.norgaard
+1  A: 

For unit tests: If an object is not the object tested, mock or stub it. In that way, you can directly control it so it returns the data that you want.

If you create a test object/object-graph, you have to set it up so that it provides the data that you want. That is probably a lot more work than you want.

For integration tests, of course you'd test a whole object graph at a time.

Lennaert
A: 

If you need to write a lot of initialization code - a mocking framework would probably help you write better, easy to understand Unit Tests.

There is no need to re write code that a mocking framework can save you.

Dror Helper
+2  A: 

It depends what you are trying to test. Unit tests with collaborators mocked out are great because

  • They are really, really fast
  • They are small and easy to understand
  • They don't have dependencies on the wider world which makes them easy to run
  • They provide excellent defect localisation

However, pure unit tests cannot tell you if you have configured your objects correctly in your IoC container, if the database connection string works etc. You need a test which runs up your IoC container and really reaches out to the Db to prove these things.

If you write as many of your tests as pure, standalone unit tests as possible then your build will stay fast. This is crucial, as a slow bulid gets run less. Even so, don't forget to add a sprinkling of wired tests to prove that your application'hangs together'.

For example, we have a (single) test for every service in our container that proves that we can request it from the IoC container. This proves we're wired up, from then on it is unit tests all the way. We have lots of pure unit tests.

The whole lot is then wrapped in some application level functional tests to prove that the app itself does what the user wants.

The thing to bear in mind is the time cost of each test type. Moving from pure unit -> wired -> functional tests costs an order of magnitude of execution time and complexity when they break.

Stuart Caborn