In this post I use a SharePoint 2010 Visual Web Part as the example. But this feature of Visual Studio can be used for any application with a UI. I’m doing a simple web part that simply adds 2 numbers together. Yes I know this is not original but it makes for a good example.

You’re required to have Visual Studio 2010 Premium or Ultimate to use Coded UI Tests

  1. Create a Visual Web Part project (don’t forget to target .Net 3.5 not 4.0)
  2. Drag 3 text boxes, 2 labels and a button on to the designer and arrange them so your web part will look similar to this:


  3. Double-click the button and add code to the event handler:


  4. Add a new Test Project to your solution and name it whatever you like
  5. Right-click on your new Test Project and add a Coded UI Test
  6. Click OK to accept the default choice of “Record actions, edit UI map or add assertions”

    UI Test Dialog

  7. Give it a few seconds and you will see the Coded UI Test Builder appear on the lower right


  8. Click the red record button
  9. Start your Visual Web Part project WITHOUT Debugging
  10. Add the Web Part to the page
  11. Put a 2 in each of the 1st 2 text boxes and click the Add button
  12. Click the Pause button on the Test Builder that has replaced the red record button
  13. Click Generate Code button (far right on the Test Builder)
  14. Give the method a name and click Add and Generate


  15. Add an Assertion by dragging the Crosshairs on the Test Builder over to the last text box intended to contain the sum. As you hover over controls they will be outlined in blue. Release the Crosshairs when last text box is selected


  16. Scroll down and select the Text property and click Add Assertion. In this case we want to make sure that our addition code is working so set the Comparison Value to 4 & the Comparator to AreEqual. Click OK. If you wish to see the test fail, you can input a different value. You can also update the code directly later in order to play with this


  17. Click the Generate Code button on the Test Builder again
  18. Give the Assertion method a name & click Add and Generate
  19. Once the code generation is complete, go back to Visual Studio’s main window and Run Tests in Current Context as seen here:


  20. Watch the magic happen!

Depending on whether you inserted a 4 or some other value, you will see one of these 2 results:



Obviously in this example we know the code works because we saw it when we recorded it. The real value here is that if and when you change your addition code in the button click event handler, you can run this test again to see if you broke anything. Or better yet, run a test like this one along with many others you would create as part of your regression testing for the solution.

Best Practices for Coded UI Tests: