2015-04-27 28 views
0

我有以下視圖模型單元測試的ICommand與NSubstitute

public class MyViewModel : IMyViewModel 
{ 
    private readonly IMyModel myMode; 
    private ICommand _myCommand; 

    public MyViewModel(IMyModel model) 
    { 
     _model = model; 
    } 

    public ICommand MyCommand 
    { 
     get { return _myCommand ?? (_myCommand = new RelayCommand(x => MyMethod())); } 
    } 

    private void MyMethod() 
    { 
     _model.SomeModelMethod(); 
    } 
} 

其中IMyViewModel是defind作爲

public interface IMyViewModel 
{ 
    ICommand MyCommand { get; } 
} 

和我的模型界面目前定義爲

public interface IMyModel 
{ 
    void SomeOtherCommand(); 
} 

我的單元測試(使用NSubstitute)我想檢查一下,當MyCommand被調用時,我的模型接收到對其會見的呼叫hod SomeModelMethod。我試過了:

[TestMethod] 
public void MyViewModel_OnMyCommand_CallsSomeOtherMethodOnModel() 
{ 
    var model = Substitute.For<IMyModel>(); 
    var viewModel = Substitute.For<IMyViewModel>(); 

    viewModel.MyCommand.Execute(null); 

    model.Received().SomeOtherMethod(); 
} 

但這目前沒有工作。當我的ViewModel上的命令被調用時,如何最好地測試我的Model方法被調用?

+0

與其爲viewModel創建一個substiture,你可能要做'new viewModel(model.object)',或者任何替代等效物。你不想嘲笑你實際測試的對象。 – forsvarir

回答

2

不知道你爲什麼嘲笑IMyViewModel在這裏。你說你想測試當你執行MyViewModel中的命令時是否調用SomeOtherMethod

你不應該在這裏嘲笑MyViewModel

[TestMethod] 
public void MyViewModel_OnMyCommand_CallsSomeOtherMethodOnModel() 
{ 
    var model = Substitute.For<IMyModel>(); 
    var viewModel = new MyViewModel(model); 

    viewModel.MyCommand.Execute(null); 

    model.Received().SomeOtherMethod(); 
} 

P.S:我不熟悉nsubstitute。但是這個想法還是一樣的(你不應該模擬MyViewModel)。確保你在nsubstitute中使用正確的方法。

+0

謝謝,但Visual Studio現在大聲呼籲,當試圖調用'viewModel.MyCommand(null)'時,需要Method,Delegate或Event。我仍然不清楚如何正確調用ICommand。有什麼建議麼? –

+0

D'oh。它應該閱讀'viewModel.MyCommand.Execute(null)'謝謝 –

+0

@JamesB哈,我複製你的代碼,並作出相同的錯字:)很高興,你解決了它。 –