views:

32

answers:

1

Hi,

My questions is the following: how can I test if an ICommand's Execute method was called on a mock object ?

I'm using the following code:

var mockOperandVM = new Mock<UCOperandViewModel> ();  
mockOperandVM.Setup (x => x.EditCommand).Returns (new RelayCommand<String> (x => { }));  

var toolbarTrayVM = new UCToolbarTrayViewModel (mockComponentsLocator.Object);
toolbarTrayVM.EditCommand.Execute ("Edit");
mockOperandVM.Verify (x => x.EditCommand.Execute ("Edit"), "EditCommand with 'Edit' parameter was not executed on the mock object.");

I have to specify here that I have an EditCommand ICommand on the UCOperandViewModel too and I want to test whether that ICommand gets executed when I call EditCommand.Execute on the toolbarTrayVM.

I get an ArgumentException on the call to Verify. It says that "A matching constructor for the given arguments was not found on the mocked type.".

Thanks in advance.

A: 

Inject the service into the SUT - preferably using Constructor Injection. That would enable you to write unit test code like this:

var mock = new Mock<IService>();

var sut = new MyViewModel(mock.Object);
sut.SomeCommand.Execute(null);

mock.Verify(s => s.Foo());

This example uses Moq.

Mark Seemann