我正在开发一个WPF带有MVVM模式的应用程序.
我知道这个MVVM模式很适合分离GUI应用程序和逻辑,所以我可以GUI独立地测试和逻辑.
但是,如果我需要向用户发送一些消息,是否最好使用messageBox?因为我正在阅读一些解决方案,所有这些解决方案都尝试将新视图实现为视图模型......等等.但我看不到实用程序.
我的意思是,如果我想向用户通知某些内容,我的结果取决于用户的决定,我如何分离我的测试(GUI和逻辑)?不直接使用messageBox而不是使用viewmodel的新视图以及所需的所有额外工作有什么好处?因为在这两种情况下,我的结果都取决于用户的决定.在这种情况下如何测试我的应用程序?
因为我正在阅读一些解决方案,所有这些解决方案都尝试将新视图实现为视图模型......等等.但我看不到实用程序.
如何对打开消息框的方法进行单元测试?
如果规范发生更改并且您需要使用其他(自定义)消息框,或者甚至只记录错误(稍后将在摘要报告中显示),该怎么办?然后你需要找到并替换每一个msgBox.Show电话.
我的意思是,如果我想向用户通知某些内容,我的结果取决于用户的决定,我如何分离我的测试(GUI和逻辑)?
通过创建一个事件,当您需要做出决定时触发该事件.然后你就得到了决定.你不在乎它来自哪里.
因为在这两种情况下,我的结果都取决于用户的决定.在这种情况下如何测试我的应用程序?
非常简单.你只是模仿你的用户回复.您可以(也可能应该)测试两种可能的场景,因此只需附加两个"假"事件处理程序:一个返回肯定决策,一个返回否定决策,就像您的用户在某些消息框中实际点击了"是"或"否"一样.
例如,请参阅http://joyfulwpf.blogspot.com/2009/05/mvvm-communication-among-viewmodels.html.
ASpirin建议注射通知器也是一个很好的设计选择.
一些粗略,过于简化的实现:
using System;
using System.Windows.Forms;
namespace Demo
{
public delegate bool DecisionHandler(string question);
/// <remarks>
/// Doesn't know a thing about message boxes
/// </remarks>
public class MyViewModel
{
public event DecisionHandler OnDecision;
private void SomeMethod()
{
// something...
// I don't know who or what replies! I don't care, as long as I'm getting the decision!
// Have you made your decision for Christ?!! And action. ;)
var decision = OnDecision("Do you really want to?");
if (decision)
{
// action
}
else
{
// another action
}
}
}
class Program
{
static void Main(string[] args)
{
// this ViewModel will be getting user decision from an actual message box
var vm = new MyViewModel();
vm.OnDecision += DecideByMessageBox;
// unlike that one, which we can easily use for testing purposes
var vmForTest = new MyViewModel();
vmForTest.OnDecision += SayYes;
}
/// <summary>
/// This event handler shows a message box
/// </summary>
static bool DecideByMessageBox(string question)
{
return MessageBox.Show(question, String.Empty, MessageBoxButtons.YesNo) == DialogResult.Yes;
}
/// <summary>
/// Simulated positive reply
/// </summary>
static bool SayYes(string question)
{
return true;
}
}
}
Run Code Online (Sandbox Code Playgroud)