2012-05-01 165 views
2

我有以下方法:使用MOQ測試此代碼的正確方法是什麼?

public void MoveChannelUp(string channelName) 
    { 
     var liveChannels = _repository.GetChannels<LiveChannel>(); 

     var channels = GetModifiedChannelsList(channelName, liveChannels); 

     _repository.SaveChannels(channels); 
    } 

我想,這樣的正確的渠道參數傳遞給建立在SaveChannels的期望()調用

我想:

channelsRepository.Setup(x => x.SaveChannels(reorderedChannels)); 

其中reorderedChannels是我期望的GetModifiedChannelsList()調用將返回,但我得到了模擬驗證異常(可能是由於重新排序的Channel不同於頻道???)

所以這是GetModifiedChanneslsList(),我真的想測試(我知道我可以使用反射來測試這一點)

那麼,如何檢驗正確的頻道列表被傳遞到SaveChannels()?

+0

我對Moq也相當陌生。也許你可以試試Moq'It'幫手,我試過了,看到一個例子:http://www.ienablemuch.com/2012/02/primer-on-unit-testing-with-moq.html –

回答

3

你可以做這樣的事情(我假設有一個名爲Channel類型和SaveChannels參數是List<Channel>;替代實際):

var expectedChannels = new List<Channel> { new Channel() }; // set up expected channels here 

var channelsRepo = new Mock<IChannelsRepository>(); 

// perform your unit test using channelsRepo here, for example: 

channelsRepo.Object.SaveChannels(new List<Channel> { new Channel() }); 

channelsRepo.Verify(x => x.SaveChannels(It.Is<List<Channel>>(l => l.SequenceEqual(expectedChannels)))); // will throw an exception if call to SaveChannels wasn't made, or the List of Channels params did not match the expected. 

這段代碼也被驗證SaveChannels方法被正確的頻道列表至少調用一次。如果沒有發生,Verify會拋出異常,並且您的單元測試將按預期失敗。

+0

謝謝,我嘗試了.CallBack(),這似乎工作,但我喜歡你的解決方案,因爲它更清晰。順便說一句,不應該channelsRepo.Object.SaveChannels(新列表 {新頻道()});下注channelsRepo.Object.SaveChannels(exceptedChannels}); ?? –

+2

@JD:也許你已經這樣做了,但是你還必須確保在'Channel'上實現了'Equals'(因此'ToHashCode')。否則,我認爲你會得到參考平等而不是邏輯平等。 –

+0

@JD:在您的實際單元測試中,您不會顯式調用channelsRepo.Object.SaveChannels;這意味着你的MoveChannelUp方法會調用它,指定從GetModifiedChannelsList得到的通道。畢竟,關鍵是你要測試GetModifiedChannelsList是否返回你期望的頻道列表。 – HackedByChinese

相關問題