我正在学习TDD和MVP模式。我创建了一个简单的WinForms应用程序,它类似于TOAD SQL工具的替代品。我正在尝试回去为我已编写的代码编写测试(我知道这不是TDD的正确过程,但请耐心等待。)
在我的表单测试类中,我想测试具体的Presenter
,但是模拟出WinForm,因为演示者在其中有应该测试的真实逻辑。但是,当我使用Moq模拟视图时,我没有看到预期的结果。在下面的代码中,前两个测试PASS,但第一个Assert上的第三个FAILS。
当我将调试器附加到NUnit并运行时,Environment
属性在调用Environments.Test
时未设置为presenter.IsDangerousSQL
:
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类中,因为它表示业务逻辑而不是直接对用户操作做出反应?
谢谢!
安迪
答案 0 :(得分:1)
假设您正在测试的代码正在检查Environment属性,您希望使用SetupGet而不是SetupSet(即告诉模拟调用其环境属性时要返回的内容)
mockWindow.SetupGet(s => s.Environment).Returns(Environments.Test);
这是因为你没有在你得到它的代码中设置属性。
或者,如果您想将Environment属性视为标准属性,那么当您编写
等语句时,您正在执行此操作mockWindow.Object.Environment = Environments.Test;
您可以使用
mockWindow.SetupProperty(qf => qf.Environment);
我个人更喜欢第一种方法。