Unit test ViewModels using IoC

Oct 22, 2010 at 10:27 AM

Hi!

I have looked at the sample "Simple MDI with Screen Collections". I have added functionality to use the unity IoC container in the sample registered like in the "customizing bootstrapper sample". Thus my implementation of ShellViewModel.OpenTab looks like:

public void OpenTab()
{
    var tab = IoC.Get<TabViewModel>();
    tab.DisplayName = "Tab " + count++;
    ActivateItem(tab);
}

Now I would like to write a unit test for this, I have added the following test method:

[TestMethod]
public void TestMethod1()
{
    ShellViewModel shellViewModel = new ShellViewModel();
    shellViewModel.OpenTab();
}

This of course failes on the call to IoC.Get. How should I solve this? Is it even meant that I should use the IoC like I do in the OpenTab method?

Coordinator
Oct 22, 2010 at 1:30 PM

Generally speaking, the IoC static gateway is intended to be used by the framework itself and similar framework extensions, and you shoudld avoid using it inside your application code. You should consider having a function injected into the view model that needs to do the creation. Something like this:

public class ShellViewModel
{
    public ShellViewModel(Func<TabViewModel> createTab){ ... }

    public void OpenTab(){
        var tab = createTab();
        tab.DisplayName = "Tab " + count++;
        ActivateItem(tab);
    }
}
This allows you to provide your own Fun<TabViewModel> at test time and enables the ShellViewModel to declare exactly what it needs to create. If this won't meet your needs, you can actually set the IoC public field funcs to your own method implementations designed to work in tests.

Oct 25, 2010 at 6:13 AM

Ok, tanks for the very quick reply. I did understand that IoC might not be intended to use by user code, that is hinted somewhere in the tutorial/blog. But nothing about how to do it instead. I could of course have come up with some sort of solution myself. However, better to ask the question rather than guessing.