【问题标题】:Moq with WinForms MVP Pattern - Failing Test具有 WinForms MVP 模式的起订量 - 未通过测试
【发布时间】: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。如果不是(例如,非视图客户端也需要它),它可能应该深入到模型或实用程序类中。

标签: winforms tdd moq mvp


【解决方案1】:

假设您的测试代码正在检查您想要使用 SetupGet 而不是 SetupSet 的 Environment 属性(即告诉模拟在调用其环境属性时要返回什么)

mockWindow.SetupGet(s => s.Environment).Returns(Environments.Test);

这是因为您没有在获取它的代码中设置该属性。

或者,如果您想将 Environment 属性视为标准属性,这就是您在编写类似语句时所做的事情

mockWindow.Object.Environment = Environments.Test;

你可以使用

mockWindow.SetupProperty(qf => qf.Environment);

我个人更喜欢第一种方法。

【讨论】:

  • 非常感谢!!如果我结合 mockWindow.Object.Environment = Environments.Test; 第二种方法不起作用使用 mockWindow.SetupProperty(qf => qf.Environment);。我同意第一种方法是要走的路。谢谢!!
猜你喜欢
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多