Skip to content
paullefebvre edited this page Sep 19, 2014 · 1 revision

Consider an application that has a method in a Calculate class that is responsible for calculating sales tax and adding it to the supplied amount. The code might look like this:

Sub AddSalesTax(amount As Currency, pct As Double) As Currency
  Return amount + (amount * 0.10)
End Sub

Granted this is a very simple method, but it does have a bug in it. The bug is obvious perhaps, but unit testing will help uncover it.

Here is an example of a XojoUnit test that tests a variety of calculations to make sure the correct result is returned. First, you need to create a test class to hold the unit test, so create a new class called "SampleTests" and set its Super to "TestGroup".

In XojoUnitController (a subclass of TestController), add this code to the InitializeTestGroups event handler:

group = New SampleTests(Self, "Sample Tests")

In the SampleTests class, add the following method to test the Calculate.AddSalesTax function:

Sub AddSalesTaxTest
  Dim calc As New Calculate
  Dim result As Currency
  result = calc.AddSalesTax(10.00, 0.10)

  Assert.AreEqual(11.00, result)

  result = calc.AddSalesTax(20.00, 0.05)
  Assert.AreEqual(21.00, result)

  result = calc.AddSalesTax(10.00, 0.07)
  Assert.AreEqual(10.70, result)
End Sub

This unit test method creates an instance of the Calculate class so that the AddSalesTax method can be called. It is called three times and its result is compared with what is expected. The comparison is done using the Assert.AreEqual method. If the two values are the same, then the test passes. If the two values differ then the test fails.

Run the project to see the XojoUnit window with the AddSalesTax test displayed in the list.

Now click the Run Tests button on the toolbar. This will run the test and display the results. In this case you’ll see that the test failed.

Clicking on the test shows the details for the test, including how long it took to run and the messages. Here you can see the messages indicate that the values that were calculated are different from what was expected. This is telling us that the AddSalesTax method has an error in its calculation. Looking back at the code, you should notice that it is using a hard-coded value of 0.10 as the percent rather than using the pct parameter.

Quit the app and go back to the code for Calculate.AddSalesTax. Update it so that it uses “pct” in place of “0.10”:

Sub AddSalesTax(amount As Currency, pct As Double) As Currency
  Return amount + (amount * pct)
End Sub

Run the project again and click the Run Tests button.

Now you will see that the test has completed successfully.

Clone this wiki locally