HAdes
HAdes

Reputation: 16993

How do you properly test the view in MVVM?

I've seen a few articles on unit testing view models in MVVM and how the tests themselves are consumers of the view models, testing the functionality of the viewModel and model. However, I'm left wondering how I go about testing the views (UI) to ensure they are wired up to my view models properly. I don't want to write a test that, for instance, presses a button to make sure something is written to the db as this is effectively testing my VM, which i've already done.

For instance, I'd like to be able to write a test to make sure that a button is wired up to a specific command. Therefore preventing anyone from coming along and removing the button's command, making it no longer functional.

Is this possible? thanks.

Upvotes: 5

Views: 2898

Answers (2)

Kent Boogaart
Kent Boogaart

Reputation: 178640

But what if someone (hopefully a designer) wants to change the Button to a MenuItem? Your test will break and you'll have to fix it. One of the major boons of MVVM is that designers can really be free to arrange and rearrange the interface however they like without requiring too much back-and-forth with the developers. Writing unit tests against the UI annuls that boon.

I'm kind of playing Devil's advocate here. I'm not saying testing the UI is completely useless and never has a place in anyone's code base. What I'm saying is that the returns are diminishing, and that you may be trading one problem for another.

As for how you actually test a view in "isolation" . . . the easiest way I think would be to use view models with injected mock services. Your view models can use a service locator to grab dependent services, so your unit tests can inject dummy services. You could then use a combination of named-element references, visual tree crawling, and the WPF UI automation APIs to assert that different visual elements have properties set as expected.

Upvotes: 4

Robin Vessey
Robin Vessey

Reputation: 4639

I think there is something from Telerik (Art of test) which can help automate the raw UI. http://www.artoftest.com/products/webaii.aspx Though now I have looked it up that is Silverlight rather than WPF. Hopefully its a good starting point at least.

Upvotes: 0

Related Questions