Exposing Bugs with Tests in Microsoft Dynamics NAV

This post is not an introduction to automated testing in Microsoft Dynamics NAV. If you don’t know what I’m talking about you should check out Luc van Vugt’s blog here first.

If you aren’t writing any automated tests for your code at the moment you should consider starting. You know that really, but it can difficult to get going. You need time to learn and become familiar with the testing framework in the first place. Then it takes time to write the tests. And then time to run them. Time you don’t have, time you’d rather spend doing something else…etc.

I Don’t Have Time

On that point, it really doesn’t take long to write tests after you’ve done your first few. There are tons of ‘library’ functions that help you create test data and documents with minimal fuss. You want to create a customer, create a sales order with an item line and then post it? That’s three lines of code.

Start with Bugs

A good place to start might be with bugs. Half the challenge with writing tests is defining exactly what you’re testing i.e. “given some initial scenario when X happens the expected result is Y.” Breaking a big codebase into snippets like that can seem daunting. With a bug you’ve got all the information you need. “Under these circumstances, when X happens we are getting Z when we were expecting Y.”

1. Write the Test First

Rather than diving into the code to find and fix the cause of the problem, take a minute to write a test for it. Recreate the steps that are leading to the bug in your test. Run the test and confirm that it fails.

Why write the test first? If you are going to use the test to confirm that the bug has been fixed (and doesn’t reappear sometime in the future) you want to be sure that the test itself works. If you write the test after the fix and it passes is that because you’ve fixed the problem or because the test is incorrect and will always pass?

Capture the bug while you’ve got the steps and the code to reproduce it. That way, you know that you’re looking at the right thing and that you’re actually fixing the issue.

2. Fix the Bug

Now you can go ahead and put the bug fix in.

3. (Re)Run the Test

Once you think you’ve fixed the problem you can run the test and confirm that it now passes. A test that passes having previously failed ought to give you a lot more confidence than one that has always passed.

Even better, you’ve added a test to your library that you can re-run when you make future changes to your code. You’re much like likely to reintroduce a bug that you’ve seen before if you’ve got a test that is specifically looking out for it.

Leave a Reply