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!

Unit Testing – Keeping Your Code Running

Now that we have code that’s starting to resemble something usable, it’s high time to put in some Unit Tests. I’m using NUnit as my testing framework, but feel free to choose something else. First off, I like to keep my tests organised, so I usually create a folder tree in my solution. In this case I start by adding the following folder structure: Testing -> GoalBuddy for the tests of my common code. Inside that folder I then create a new NUnit3 unit test project.

Two things to mention here: after you install the NUnit test runner and templates, you can create four different kinds of test projects: Android, iOS and UWP, located under “Cross-Platform”, and a platform independent one, located under “Test”. Choose the last one for unit testing your common code.

The other thing to do is to make sure your unit test project is compatible with .NET Standard. Out of the box, your common code will be in a .NET Standard 2.0 library, so your test project needs to reference .NET 4.6 or higher.

Now add a reference to the project that holds your common code to your unit test project, build your solution and run the default test as a sanity check.

Next, let’s add a test that checks that data actually gets loaded into the ViewModel:

Now you can see that, although the test should run without problems, this is already a bit weird. I assert that the ViewModel should have 3 ToDoItems, but I never arrange for that. Right now that’s hard coded into the constructor of my ViewModel, which is really bad for testing. What if I want to add another test that tests for the correct behaviour if my repository throws an exception?

Sure, I could change my repository to do that, but then it will always do that, of course, but that would then cause the test I just wrote to fail. Not great. And that’s where Dependency Injection comes in – more on that in my next post!

Asynchronous Loading of Data – a Better Way

When last we left off, we were loading the data for the ViewModel inside its constructor – a bad idea, because the data loading is done asynchronously, and constructors can’t be made async. So we need to find a better way to do that.

First off I want to factor the process of loading the data out to its own method inside my OverviewVM class:

With this public method I’ve got more options on handling the data. So the question is: do I really need to load the data right when my View Model is constructed? Actually, no. I don’t need the data until my View appears – and the OnAppearing() method can be made async to accommodate the asynchronous nature of data loading.

Because I need a reference to my View Model in OnAppearing(), I’m storing it in a field for now. Later on, when we get to decoupling our classes, that’s going to be done a better way, but for now this will do the job.

Except that there’s a little problem now. Because the data we’re binding to is not already in place when the page appears, our list of ToDo’s is empty. We need to explicitly tell our View that our collection of ToDoItems has changed.

I could do this by making my ViewModel implement the INotifyPropertyChanged interface – but fortunately MVVMLight already has a base class in place that will handle all of that for me. All I need to do is to make my View Model inherit from ViewModelBase and use ViewModelBase’s Set method, which handles both the assignment and notification for me.

The resulting View Model now looks like this:

So, another hurdle jumped. The code is slowly starting to look better, but still suffers from tight coupling. More on this next!

Repositories – Getting the Data to the ViewModel

Right now the ViewModel is pretty hideous. It shouldn’t be responsible for fetching the data, much less creating it – that’s a clear violation of the Single Responsibility Principle and all round Bad Idea (TM). So let’s make that the responsibility of a repository.

I have a go-to repository interface that I use as a starting point:

IEntity is there purely to make sure that the class in the repository has an Id field. Feel free to leave it out if you don’t need it, but it’s useful if you want to have a unique identifier for retrieving/updating entities in your repository.

For use with SQLite, I use IEntity to create a primary key on the Id:

…and then I make my ToDoItem class inherit from it.

Now my ToDoItem class fulfils all the requirements for use in a repository that implements IRepository<T>. Eventually I want that to be a repository that uses SQLite, but for now I’m going to use a bare-bones mock-up with some hard-coded data.

I’ll use this later in unit testing, so creating it is not actually a waste of time.

and now, finally, I can change my ViewModel to use this repository:

Now, looking at this, the ViewModel is still in a world of wrong. In fact, it’s so wrong that almost every line in it needs to be changed. We have tight coupling, we are blocking the UI thread because you can’t use ‘await’ in a constructor, we’re using a mock repository and an unsuitable collection, but fear not – all this will be addressed over the course of the next few posts…