Dependency Injection – Keeping Your Tests Independent

In this post I’m going to look at how to resolve the problem of how tight coupling in code causes problems for unit tests. What we have at the moment is a View Model that is tightly coupled to a repository, which makes it hard to impossible to test the View Model’s behaviour for cases like the repository throwing an exception, or being unavailable.

The way around this is by using a technique called Dependency Injection. There are many, many articles written on this subject, so I won’t go into too much depth here. I do encourage you to read up on this, because there are a few different ways of using DI.

In this case I’m going to use the most common one, which is constructor injection. Constructor injection simply means that we’re going to inject an instance of the repository through the constructor, like this:

As you can see, it’s very simple. Instead of creating the repository inside the constructor like before, we pass it as an argument. It still gets stored in the same private field, and if it’s null, we throw an exception. The exception is not necessary, of course, but in this case it makes sense because the View Model rather depends on having a valid repo to do its job.

Changing the constructor means that now the project will no longer compile, of course, so we need to go in and change a few more things.

First off, since we’re looking at unit testing, let’s change the test setup:

While this is still using the old mock repository, it’s now possible to use different repos in further tests. I’m also going to create a second test to test that passing a null argument will throw the correct exception:

The final step is to change the construction of the OverviewVM in the constructor of the OverviewPage class. For now let’s just inject null. It means that the app won’t run because of the exception that will get thrown, but it will compile so that you can run the tests.

Well, that’s it for now. In the next post I’m going to create more tests and introduce you to mocking frameworks – fun times ahead!

Leave a Reply

Your email address will not be published. Required fields are marked *