【发布时间】:2012-09-04 01:07:46
【问题描述】:
我正在学习 TDD 和 MVP 模式。我创建了一个简单的 WinForms 应用程序,它类似于 TOAD SQL 工具的替代品。我现在正试图回去为我已经编写的代码编写测试(我知道这不是 TDD 的正确过程,但请多多包涵)。
在我的表单测试类中,我想测试具体的Presenter,但模拟出 WinForm,因为演示者中包含应该测试的真实逻辑。但是,当我使用 Moq 模拟视图时,我没有看到预期的结果。在下面的代码中,前 2 次测试通过,但第 3 次在第一个 Assert 上失败。
当我将调试器附加到 NUnit 并运行时,当调用 presenter.IsDangerousSQL 时,Environment 属性未设置为 Environments.Test:
private Mock<IQueryForm> mockWindow;
private QueryFormPresenter presenter;
/// <summary>
/// Runs ONCE prior to any tests running
/// </summary>
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
//We're interested in testing the QueryFormPresenter class here, but we
//don't really care about the QueryForm window (view) since there is hardly any code in it.
//Therefore, we create a mock of the QueryForm view, and pass it to the QueryFormPresenter to use.
mockWindow = new Mock<IQueryForm>();
presenter = new QueryFormPresenter(mockWindow.Object);
}
[Test]
public void User_Can_Execute_Selects_From_Any_Environment()
{
Assert.AreEqual(false, presenter.IsDangerousSQL("select 1"));
}
[Test]
public void User_Cant_Execute_Schema_SQL_On_Any_Environment()
{
Assert.AreEqual(true, presenter.IsDangerousSQL("alter table"));
Assert.AreEqual(true, presenter.IsDangerousSQL("DrOp table"));
}
//Updates, Deletes and Selects are allowed in Test, but not in Production
[Test]
public void User_Can_Only_Execute_Updates_Or_Deletes_Against_Test()
{
//mockWindow.SetupSet(w => w.Environment = Environments.Test);
mockWindow.Object.Environment = Environments.Test;
Assert.AreEqual(false, presenter.IsDangerousSQL("update "));
Assert.AreEqual(false, presenter.IsDangerousSQL("delete "));
//mockWindow.SetupSet(w => w.Environment = Environments.Production);
//mockWindow.Object.Environment = Environments.Test;
Assert.AreEqual(true, presenter.IsDangerousSQL("update "));
Assert.AreEqual(true, presenter.IsDangerousSQL("delete "));
}
我非常感谢任何人可以提供的任何见解!此外,IsDangerousSQL 方法是否应该在 Model 类中,因为它代表业务逻辑,而不是直接对用户操作做出反应?
谢谢!!
安迪
【问题讨论】:
-
你能解释一下注释掉的代码吗?看起来你应该使用它。
-
如果代码与“视图的呈现”相关,它应该驻留在 VM 中 - 例如,您想突出显示错误的 sql。如果不是(例如,非视图客户端也需要它),它可能应该深入到模型或实用程序类中。