So let’s say you’ve got a ViewModel with the following method:
And you need to make some changes to it. Of course, because we’re good developers, we make sure to check if there’s some tests for the method before we make our changes. Luckily, someone already has written a test:
But wait a second – this test doesn’t look like it tests everything. Sure it calls the method and tests the result, but there are a few conditions in there that your test doesn’t seem to cover.
You have two options: you could debug or manually trace through the method to try to determine in your head or on paper if all cases are covered, or you could click the “dotCover” button on your toolbar
dotCover is a tool created by JetBrains (those wonderful people who made Resharper and other developer tools) which analyses your unit tests and keeps track of exactly what lines of code your tests invoke. Using this information, it can determine how much of your code is unit tested and exactly which lines are covered. Running “Cover All Tests In Solution” from your Resharper > Unit Tests menu gives you:
The bottom half of the image shows the test coverage, broken down by assembly, namespace, type, and all the way into individual members. It expresses the coverage as a percentage as well as the number of relevant statements covered compared to the total statements.
As you can see here, the method we’re dealing with is only 61% covered (as we feared), so let’s go see what lines aren’t tested.
dotCover allows you to highlight the tested lines of code (green) and the untested lines of code (red). This makes it a LOT easier to tell what unit tests you could write, and identify if the area of the codebase you’re working in is backed up by tests. We can see two distinct areas we haven’t tested yet, so let’s go write a test.
After adding the above test, which exercises the “foreach” portion of the code, we can go back to the Unit Test Sessions window to review our new unit test and code coverage:
You can see here, because of the new unit test, two warnings come up: Coverage snapshot out of date and Coverage Analysis not started yet. Because of the extra processing dotCover requires to actually tally and mark each line of code covered by unit tests, it only runs when you tell it to. You can get it to refresh by highlighting the test(s) you want to analyze and clicking the dotCover icon in the toolbar.
After re-analyzing, you can see our test coverage has skyrocketed to 90%, and checking the source code verifies that we have indeed covered the foreach loop (but still have another test to go)