Brand new to vb.net and unit testing, hoping for some simple help
I am trying to unit test for data being input into a textbox (txtPrice). If it is not numeric, it throws a messagebox stating that the input must be numeric. However, when I unit test, I can't figure out why my test fires the message box twice. THis is my (simple) unit test:
Public Sub txtBoxes_LeaveTest()
Dim target As frmEstimate_Accessor = New frmEstimate_Accessor ' TODO: I开发者_运维知识库nitialize to an appropriate value
Dim sender As Object = Nothing ' TODO: Initialize to an appropriate value
Dim e As EventArgs = Nothing ' TODO: Initialize to an appropriate value
sender = target.txtPrice.Text
target.txtPrice.Text = "112L"
Dim expected As String
Dim actual As String
expected = "112L"
target.txtBoxes_Leave(sender, e)
actual = target.txtPrice.Text
Assert.AreEqual(expected, actual, "txtPrice.leave event not functioning correctly")
End Sub
My understanding is that for unit testing, you declare the sender, and (in this case) set the sender to some value that will trip the message box. 112L should do this on the leave event. I then write my expected, which in this case is 112L, fire the event, and then get the actual out of the text box. I then Assert.AreEqual to ensure the expected and actual are the same.
First, is this correct? And second, why does it fire twice?
Thank you.
You don't want unit tests that cause message boxes to appear. A big part about unit testing is being able to run them automatically, and things like MsgBox and textbox values break that.
What you want to do here instead is narrow the scope of your testing. Your leave event should call out to a separate validation method. Based on the result of the method, your leave event may make changes to the form. The method will accept a string as an input and either return a boolean value whether the string is valid, return a corrected string, or throw an exception. Write your test against that method. What you want to do is have a unit test that verifies whether this validation method is doing what it is supposed to.
Use sender
only if the Procedure name handles different control events.
you can do it like this:
Private Sub txtPrice_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPrice.Leave
If Not IsNumeric(txtPrice.Text) Then
MsgBox("txtPrice is not numeric!", MsgBoxStyle.Critical, "Error")
txtPrice.SelectAll()
txtPrice.Focus()
End If
End Sub
精彩评论