Friday, March 24, 2017

Introducing NUnit on Visual Studio 2010 in Visual Basic

As part of my research on Xamarin I started looking at NUnit as a unit tester. I was curious to see how I would implement it on my Visual Basic Purchasing project. We are still using Visual Studio 2010 so the implementation details are a little different. But it can be done.

Let's start by installing NUnit.

Installing NUnit

Start Visual Studio 2010
In the menu click Tools -> Extension Manager
On the left, click Online Gallery.
In the search area, enter NUnit and hit Enter.
Scroll down to "Visual NUnit 2010" and select it.
Hit [Download]
Restart Visual Studio


Creating the project to be tested

Start a new class library project and call it "Calc".
Rename "Class1" to "Add"
Add a public method called Add so the code looks like this.

Public Class Add

    Public Function Add(op1 As Integer, op2 As Integer) As Integer
        Return op1 + op2
    End Function
End Class

Build the project

Creating the test project

Right-click on the Add class and select "Create Unit Tests..."
Ensure only "Add(System.Int32, System.Int32)" is checked and click [OK]. You don't need to create a test for the class's constructor. When prompted for the new project's name call it "CalcTest".


Open the CalcTest project, open AddTest.vb. In the AddTest method you may need to change "Add" to "Add.Add".

Change op1 value to 1, op2 value to 2, expected to 3. Remove the Assert.Inconclusive line.

    <TestMethod()> _
    Public Sub AddTest()
        Dim target As Add.Add = New Add.Add()
        Dim op1 As Integer = 1 
        Dim op2 As Integer = 2         
        Dim expected As Integer = 3 
        Dim actual As Integer
        actual = target.Add(op1, op2)
        Assert.AreEqual(expected, actual)
    End Sub

Make CalcTest the startup project.

Run the application. You will see a Test Results window that looks like this.


Now go back to Calc.Add and change the Add method to replace the "+" with "-" like this.

Public Class Add

    Public Function Add(op1 As Integer, op2 As Integer) As Integer
        Return op1 - op2
    End Function
End Class

Rebuild and run again. The "Test Results" panel will now show an error.


No comments:

Post a Comment