This project is read-only.

Tests with dependency injection

When you are developing with unit tests, you'll often find the production code utilises third party API.

This presents a problem, that is how do you unit test against a real system? I mean there might be reason why you cannot develop against the real system. For instance the system may not be available to you, only the API, or the system just runs too slowly for your unit tests, or requires too much setup.. So you need a way of tricking the code you are developing into thinking it is running against the real system.

Your code is dependent on the real system, it has a dependency on it in order to run.

One way in fooling the code under test that it is running against the real system is to substitute the implementation of the real system with a fake system. What we do is pass the depenency into the code rather than it decide what to use, that way we can pass in (inject) a fake system into the code whilst our unit tests are running.

There is a pattern called dependency injection, that helps the developer do just this. We recommend if you don't fully understand Dependency Injection you read this article before looking at the example.

This is a popular pattern used in unit testing, we have used this pattern in many areas of Shweet, to see an example of code that uses DI goto the following code link :-

To see the unit test code goto the following code link :-

Last edited Apr 7, 2010 at 1:17 PM by jamesafisk, version 14

Comments

No comments yet.