How do you properly test the view in MVVM?

c#, mvvm, wpf, xaml

Solution

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.

Problem

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.

Original source