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!

Leave a Reply

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