Now that we have successfully tested our CalculateDistance
method we can test our web page to make sure the btnCalculate_Click event is
Open the code behind page for the Default.aspx page.
Right click in the btnCalculate_Click event and select "Create Unit
Test…" from the pop-up menu. The Create Unit Tests dialog will appear.
Click the OK button. Visual Studio will add a new test class to the TripCalculatorTest
project called DefaultTest.cs.
Add the following using statements to the top of the DefaultTest.cs
Scroll down in the DefaultTest class to the btnCalculate_ClickTest
method. Notice the attributes associated with this method. They tell the unit
testing framework which page to launch when running this test.
Replace the code within the method with the following code.
public void btnCalculate_ClickTest()
Page page = TestContext.RequestedPage;
TextBox txtTime = (TextBox)page.FindControl("txtTime");
txtTime.Text = "5";
TextBox txtSpeed = (TextBox)page.FindControl("txtSpeed");
txtSpeed.Text = "6";
PrivateObject privateObject = new PrivateObject(page);
Button btnCalculate = (Button)page.FindControl("btnCalculate");
privateObject.Invoke("btnCalculate_Click", btnCalculate, EventArgs.Empty);
Label lblDistance = (Label)page.FindControl("lblDistance");
This code will first get a reference to the page that is
being tested. It then gets a reference to the two textboxes on the web page
and sets their text properties.
The code then creates an instance of an object called a
PrivateObject. This object is in the Microsoft.VisualStudio.TestTools.UnitTesting
namespace. This object will allow you to access private methods or objects in
your code. You should never change the scope of an object just so you can test
The Invoke method of the PrivateObject is called to fire the
btnCalculate_Click event. The code then checks that the text of the
lblDistance label matches the expected result. If you right click in this test
method and select Run Tests from the pop-up menu you will run this test.