views:

243

answers:

4

So I know that unit testing is a must. I get the idea that TDD is the way to go when adding new modules. Even if, in practice, I don't actually do it. A bit like commenting code, really.

The real thing is, I'm struggling to get my head around how to unit-test the UI and more generally objects that generate events: user controls, asynchronous database operations, etc.

So much of my code relates to UI events that I can't quite see how to even start the unit testing.

There must be some primers and starter docs out there? Some hints and tips?

I'm generally working in C# (2.0 and 3.5) but I'm not sure that this is strictly relevant to the question.

A: 

You should separate logic and presentation. Using MVP(Model-View-Presenter)/MVC (Model-View-Controller) patterns you can unit test you logic without relying on UI events. Also you can use White framework to simulate user input. I would highly recommend you to visit Microsoft's Patterns&Practices developer center, especially take a look at composite application block and Prism - you can get a lot of information on test driven design.

aku
A: 

The parts of your application that talk to the outside world (ie UI, database etc.) are always a problem when unit-testing. The way around this is actually not to test those layers but make them as thin as possible. For the UI you can use a humble dialog or a view that doesn't do anything worth testing and then put all the logic in a controller or presenter class. You can then use a mocking framework or write your own mock objects to make fake versions of the views to test the logic in the presenters or controller. On the database side you can do something similar.

Testing events is not impossible. You can for example subscribe an anonymous method to the event that throws an exception if the event is thrown or counts the number of times the event is thrown.

Mendelt
+2  A: 

the thing to remember is that unit testing is about testing the units of code you write. Your unit tests shouldn't test that clicking a button raises an event, but that the code being executed by that click event does as it's supposed to.

What you're really wanting to do is test the underlying code does what it should so that your UI layers can execute that code with confidence.

lomaxx
+1  A: 

Read this if you're struggling with UI Testing
www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf

+1 to people posting keep UIs as thin as possible. Manually test UI stuff where benefit to cost in automating it is minimal. Test everything under the UI skin ruthlessly. Use Humble Dialog, MVC or variants to keep logic and UI distinct and loosely coupled.

Gishu