我在WPF編寫單元測試與起訂量來測試用戶是否點擊了一個YesNoCancel
MessageBox中的「是」按鈕時,他們關閉窗戶。在我CloseCommand
我在我的視圖模型給出了當用戶關閉窗口下面的消息:以下設置不匹配,WPF MVVM單元測試與起訂量
var result = _messageSvc.Show(
"Do you want to save changes?",
"Save Changes",
Services.MessageBoxButton.YesNoCancel,
Services.MessageBoxIcon.Question,
Services.MessageBoxResult.Yes);
我_messageSvc
是一個自定義郵件服務以顯示消息框內部的私有實例。下面是服務的代碼:
public interface IMessageSvc
{
void Show(string message);
MessageBoxResult Show(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon, MessageBoxResult defaultResult = 0);
}
public class MessageSvc : IMessageSvc
{
public void Show(string message)
{
MessageBox.Show(message);
}
public MessageBoxResult Show(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon, MessageBoxResult defaultResult)
{
return (MessageBoxResult)MessageBox.Show(message, caption, (System.Windows.MessageBoxButton)buttons, (System.Windows.MessageBoxImage)icon, (System.Windows.MessageBoxResult)defaultResult);
}
}
注:MessageBoxButton
,MessageBoxIcon
,並MessageBoxResult
是枚舉我在同一個文件進行模仿什麼.NET提供開箱即用的。我不向他們展示這裏的可讀性
我的單元測試的緣故:
[TestMethod]
public void ShouldAskToSaveOnCloseRespondYesTest()
{
// Mock and setup initial user data
var u= new User
{
UserId = 1,
UserName = "FirstName LastName",
FavoriteColor = "Blue"
};
mainViewModel.UserInfo= new UserInfoDtoWrapper(u);
// assert the data has not changed yet
Assert.IsFalse(mainViewModel.UserInfo.IsChanged);
// change the user data
mainViewModel.UserInfo.UserName= "LastName FirstName";
// assert the data has changed
Assert.IsTrue(mainViewModel.UserInfo.IsChanged);
// execute window closing
mainViewModel.CloseCommand.Execute(new object());
// verify messagebox shows and the 'Yes' button is clicked
// this will then save the changes made to the user instance
var messageBox = new Mock<IMessageSvc>();
messageBox.Setup(x => x.Show(It.Is<string>(y => y == "Do you want to save changes?"),
It.Is<string>(y => y == "Save Changes"),
It.Is<MessageBoxButton>(y => y == MessageBoxButton.YesNoCancel),
It.Is<MessageBoxIcon>(y => y == MessageBoxIcon.Question),
It.Is<MessageBoxResult>(y => y == MessageBoxResult.Yes)))
.Returns(MessageBoxResult.Yes);
messageBox.Verify();
}
的錯誤出現在messageBox.Verify()
線,但是從我所看到的,我做正確。我需要獲取消息框的返回值,以繼續測試用戶單擊「是」按鈕後發生的情況,所以我不想在內部使用帶有Linq查詢的Verify
,而是需要捕獲結果。
謝謝
「錯誤發生在messageBox.Verify()行」 - 什麼錯誤? –
ShouldAskToSaveOnCloseRespondYesTest引發異常:Moq.MockVerificationException:以下設置不匹配:IMessageSvc x => x.Show(它是(y => y ==「您是否想保存更改嗎?」),它是。 (y => y ==「保存更改」)... –
安裝和驗證之間的其餘代碼在哪裏?目前沒有測試執行 –