FINALLY, AN EASY WAY FOR VB.NET DEVELOPERS TO TEST THEIR CODE
|
VB.NET developers have long searched for an easy, effective tool for unit testing their code. Typemock Isolator has come to the rescue by making it easy for VB.NET developers to write unit tests in their native language with custom Visual Basic APIs. The problem with unit testing VB.NET Typemock Isolator’s solution The VB APIs expose the entire feature set of Isolator’s powerful mocking engine. You can now mock any dependency – Frameworks like SharePoint, ASP.Net, WCF or any 3rd party libraries. You can mock Shared and NotInheitable classes, or any other code. With Typemock Isolator, VB.NET developers can now write clear, concise and effective unit tests in their language of expertise. Isolator’s VB.NET unit test in action Public Class MyForm
Private Sub MyForm_FormClosing
(ByVal sender As System.Object,
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If Me.IsDirty = True Then
Dim result As DialogResult
result = MessageBox.Show("Do you really want to close the window?",
"Confirm Closing", MessageBoxButtons.OKCancel)
If result = DialogResult.Cancel Then
e.Cancel = True
Else
e.Cancel = False
End If
End If
End Sub
Public ReadOnly Property IsDirty() As Boolean
Get
Throw New NotImplementedException
End Get
End Property
End Class
The problem is that IsDirty throws an exception. If I try to invoke the event directly, my test will fail because of this exception. In addition, even if I manage to solve this problem when calling MessageBox.Show the test will hang, waiting for a manual operation. This is decidedly detrimental to an automated test. Now let’s write a test with Isolator’s API to change the behavior of the IsDirty as well as the MessageBox.Show calls. Here is the code: <TestMethod()> Public Sub WhenClosing_IsDirtyIsTrue_UserChoseToCancel_DontCloseForm()
Dim form As New MyForm()
' Override the IsDirty property and return True
Using TheseCalls.WillReturn(True)
Dim temp = form.IsDirty
End Using
' Override the MessageBox.Show call to return OK,
' simulating a "Don't Close"
Using TheseCalls.WillReturn(DialogResult.Cancel)
MessageBox.Show("","",MessageBoxButtons.OK)
End Using
' Invoke the closing event using the Close method
form.Show()
form.Close()
' Assert the form did not close
Assert.IsTrue(form.Visible)
End Sub
As you can see, we use Isolator’s TheseCalls.WillReturn API to specify the return values of the calls. We then invoke the closing event. Because of our setup, the original code is ignored and instead returns what we specified. An isolated, easy VB.NET unit test is born. Download a free trial of Typemock’s VB.NET Unit Testing tool to start writing your own VB.Net tests or click through our resources below for all the information and support you need to effectively unit test in VB.NET. Download Typemock Isolator VB.NET Unit Testing Tool! VB.NET Unit Testing Resources:
|