我正在學習TDD和MVP模式。我創建了一個簡單的WinForms應用程序,就像TOAD SQL工具的替代品一樣。我正在嘗試回寫現在爲我已寫的代碼編寫測試(我知道這不是TDD的正確過程,但請耐心等待)。Moq與WinForms MVP模式 - 失敗測試
在我的表單測試類中,我想測試具體的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類中,因爲它代表業務邏輯而不是直接對用戶操作做出反應?
謝謝!
安迪
你能解釋註釋掉的代碼嗎?看起來你應該使用它。 – 2009-08-07 14:49:47
如果代碼與「視圖的呈現」相關,它應該駐留在VM中 - 例如,您想突出顯示錯誤的SQL。如果沒有(例如非視圖客戶端也需要它),它應該更深入到模型或實用程序類中。 – Gishu 2012-09-04 03:56:48