Handling Errors in the ViewModel

OK, this time round I’m going to look at what I want my ViewModel to do when things go wrong. If, for instance, the repository for my ToDoItems throws an exception.

Obviously I don’t want my app to crash if that happens, so I need to catch the possible exceptions and deal with them gracefully. In this instance I think I want to display an error message instead of my list of ToDoItems. What I’ll need for that is a) a label to display said error message and b) some way of toggling the visibility of my error message and list.

I can implement a) by simply adding a string property, and b) by binding the visibility of said elements to a boolean property in my ViewModel.

Now I only need to put my repository code in a try-catch block and handle exceptions:

Ok, right now I’m using a catch-all exception handler here, which is not great, but right now it’s all I need. I reserve the right to change my mind later.

In other news, I initialise my IsFaulted and ErrorMessage properties optimistically in my constructor, and only change them if things go horribly wrong while trying to get the data from the repository.

With that in place I can now add another test:

This time round I’m setting my repo mock up to throw an exception (asynchronously!) whenever the GetAsync method is called, and assert that my IsFaulted and ErrorMessage properties have the correct values.

…and now I think that’s enough testing for now. Time to go back to the app itself – in the next article!

Mocking Your Tests – Ha Ha!

Up until now we’ve been using a hand-rolled mock repository to supply data to our app and out unit tests. And while that’s a good first step, it gets clumsy very quickly when trying to cover different scenarios inside out unit tests. For instance, I want to write a test that asserts that the data from the repository is loaded correctly, but I also want to test that my ViewModel behaves correctly if the data retrieval from the repo fails for some reason.

Writing separate classes for each scenario is a tad over the top. fortunately there’s a simple solution: mocking frameworks. Mocking frameworks allow you to mock only the things you need for a test.

sounds a bit fuzzy, I know, so let me just show you how it works. the following code uses the Moq framework – there are others out there if you fancy. Anyway, here’s the code for my previous test, this time using Moq:

OK, let’s take a look at that. First off I’m creating a list of ToDoItems and populate it with a few dummy values. This is the list I want my mock repository to return when itsĀ GetAsync() method is called.

After that I create the mock for my IRepository<ToDoItem>. This will essentially have the same function as my MockRepository class before. Except that it’s a lot quicker to create, as you can see.

The following line is where the mocking magic happens. The Setup method of my repo mock takes an argument specifying which method to mock, followed by what that method call should return. Moq supports both synchronous and asynchronous methods now via Returns() and ReturnsAsync() respectively. In this case I’m setting the mock up to return the list of ToDoItems I created earlier whenever the GetAsync() method is called.

Finally I inject the mock for my IRepository<ToDoItem> into the constructor of my OverviewVM class. Note that I’m passing repoMock.Object, not just repoMock as a parameter. This is something that’ll likely catch you out the first few times. It certainly did with me.

After that the code remains the same. I call the LoadData method of my OverviewVM, which promptly returns the list I specified in the setup of my mock. Neat, huh?

…and in the same way we can now test how we want our OverviewVM to react if the repository fails to load the data for some reason. What that reactions should be – now that’s the topic of the next post…

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!