I know that in MVVM pattern (or possibly in any design pattern of this kind) we should keep our layers decoupled. From my understanding it also means, that I should keep my ViewModels separate. I'm having a bit trouble following this rule.
Say - I have a ConversationViewModel
and a MessageViewModel
- the former needs to create instances of the later. When ConversationViewModel
gets notification about incoming message it spawns a new MessageViewModel
instance and fills it with data.
The question is - if I create new MessageViewModel
instances explicitly in the ConversationViewModel
won't it make my app a bit harder to test? I mean - one unit of code is the ConversationViewModel
and other is the MessageViewModel
- I'd like to test both separate, so when somebody breaks something in the later, test for the former won't be affected. How do I achieve it?
I'm using MVVMLight, so I thought I would register MessageViewModel
as an implementation of some interface, and then create a class like MockMessageViewModel
implementing the same interface, but used only in tests. Then in the ConversationViewModel
I'd ask the IOC container to just give me the registered implementation. Is it a good approach, or am I overreacting? Example code:
public class ViewModelLocator {
public ViewModelLocator() {
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (//in test) {
SimpleIoc.Default.Register<IMessageViewModel, MockMessageViewModel>();
}
else {
SimpleIoc.Default.Register<IMessageViewModel, MessageViewModel>();
}
}
public class ConversationViewModel : ViewModelBase {
public void MessageReceived(string data) {
//I'm thinking about doing this:
var vm = SimpleIoc.Default.GetInstance<IMessageViewModel>();
// instead of doing this
var vm = new MessageViewModel();
//do stuff with vm
}
}