2009-08-07 84 views
2

我正在学习TDD和MVP模式。我创建了一个简单的WinForms应用程序,就像TOAD SQL工具的替代品一样。我正在尝试回写现在为我已写的代码编写测试(我知道这不是TDD的正确过程,但请耐心等待)。Moq与WinForms MVP模式 - 失败测试

在我的表单测试类中,我想测试具体的Presenter,但是模拟出WinForm,因为演示者具有应该测试的真实逻辑。但是,当我使用Moq嘲笑视图时,我没有看到预期的结果。在下面的代码中,前两个测试PASS,但是第一个Assert的第三个FAILS。

当我调试器附加到NUnit的和跑,Environment属性未设置为Environments.Testpresenter.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

你能解释注释掉的代码吗?看起来你应该使用它。 – 2009-08-07 14:49:47

+0

如果代码与“视图的呈现”相关,它应该驻留在VM中 - 例如,您想突出显示错误的SQL。如果没有(例如非视图客户端也需要它),它应该更深入到模型或实用程序类中。 – Gishu 2012-09-04 03:56:48

回答

1

假设下测试你的代码检查环境属性,你想使用SetupGet代替SetupSet(即告诉了模仿什么返回时,其环境属性的叫法)

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

这是因为您没有在代码中设置属性。

或者,如果你想Environment属性当作一个标准的属性,这是你在做什么,当你写这样

mockWindow.Object.Environment = Environments.Test; 

语句可以使用

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

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

+0

非常感谢!第二种方法不起作用,但如果我将mockWindow.Object.Environment = Environments.Test;与mockWindow.SetupProperty(qf => qf.Environment);.我同意,第一种方法是要走的路。谢谢!! – Andy 2009-08-14 14:26:30