Visual Basic .NET Language Unit Testing for Tax Calculation


Example

This example is divided into two pillars

  • SalaryCalculation Class : Calculating the net salary after tax deduction
  • SalaryCalculationTests Class : For testing the method that calculates the net salary

Step 1: Create Class Library, name it WagesLibrary or any appropriate name. Then rename the class to SalaryCalculation

''' ''' Class for Salary Calculations ''' Public Class SalaryCalculation

    ''' <summary>
    ''' Employee Salary
    ''' </summary>
    Public Shared Salary As Double

    ''' <summary>
    ''' Tax fraction (0-1)
    ''' </summary>
    Public Shared Tax As Double

    ''' <summary>
    ''' Function to calculate Net Salary
    ''' </summary>
    ''' <returns></returns>
    Public Shared Function CalculateNetSalary()
        Return Salary - Salary * Tax
    End Function
End Class

Step 2 : Create Unit Test Project. Add reference to the created class library and paste the below code

Imports WagesLibrary 'Class library you want to test

''' <summary>
''' Test class for testing SalaryCalculation
''' </summary>
<TestClass()> Public Class SalaryCalculationTests

    ''' <summary>
    ''' Test case for the method CalculateNetSalary
    ''' </summary>
    <TestMethod()> Public Sub CalculateNetSalaryTest()
        SalaryCalculation.Salary = 100
        SalaryCalculation.Tax = 0.1
        Assert.AreEqual(90.0, SalaryCalculation.CalculateNetSalary(), 0.1)
    End Sub
End Class

Assert.Equal checks the expected value against the actual calculated value. the value 0.1 is used to allow tolerance or variation between expected and actual result.

Step 3 : Run the test of the method to see result enter image description here

Test result enter image description here