Unit Testing Tips - Forms

Posted by Mary Harvey on Apr 7, 2015 11:06:00 AM
Mary Harvey
Find me on:


The Visual Studio Unit Test functionality is ideally suited for testing class library methods rather than windows or web forms, but in this blog, I’d like to share some process steps that may not be obvious, but can enhance reuse and save you a lot of unnecessary builds and rework.  

User Interface automated testing is primarily done using other tools that can record and play back a user session (e.g. Coded UI Tests with Visual Studio Premium or Ultimate or the HP Unified Functional Testing (formerly from Mercury) or SmartBear TestComplete).

A limited amount of automated “unit testing” can be performed on a form event by making it public and then creating a unit test that instantiates the form and calls the click method.  However, if that click method simply brings up another window, then this approach will not work.

To avoid building a test application to debug and test a child form in a separate assembly, the following process can be used to test it prior to its integration with a larger application.  While this test cannot be used for automated testing, it will save the building of multiple small test applications and the test will then be available for any developer who needs to maintain the form.

Protecting the Form from “Auto-kill”

The problem with loading non-modal MDI forms from a unit test is that the load event fires and completes and this then allows the test process to end and kills the life of the form as well.  Thus, the test thread must be blocked from completing until the tester is done working with the form.  This can be accomplished by launching a message box after the form is shown which will keep the process from completing until the message box closes.

A static test utility method can be added to all test projects to accomplish this task:


Then a test method is added to show the form to be launched for testing:


Topics: Microsoft, Visual Studio, Unit Testing