having fun with code coverage

If you’re lucky enough to have one of the team editions of Visual Studio 2005, you’ve probably got unit testing built in (well unless you’ve got the architect version).  I must admit, I’m not big on test driven development, but I do like code testing and LOVE code coverage.  So a fun thing you can do with code coverage is actually run your windows app, and see what code gets “touched”.  It’s a good way to exercise the UI.


Here’s how you do it in VB.NET 2005…


I’m assuming you have Vb’s application framework turned on.  In which case VB generates a Shared Sub Main for you at compile time.  this is the method you want to have your unit test call.  Problem is, the unit testing won’t do that because the Sub Main is compiler generated… but’ there’s an easy trick to get there.  What I do is from the Project properties, Application tab, click on the View Application Events button on the bottom of the screen.  Next add the following code:

Private Shared Sub Main2(ByVal args() As String)
Main(args)
End Sub

Then right click on the procedure and select Create Unit Tests, and make sure you turn on code coverage. That’s it. you’re ready to run. smile 


Run the tests, work that UI and see how much of your code gets covered.  Ideally the only things not covered will be the exception handling code, in which case you can then devise scenarios to test that too.  Reviewing what parts of your code actually get hit has never been so easy.  Enjoy smile


If you don’t want to leave that Main2 in your code, you can easily modify the code that is in the VSCodeGenAccessors, changing Main2 to Main. In particular where it uses reflection.