NUnit + Moq抛出异常

时间:2009-08-14 20:49:41

标签: c# tdd nunit moq

接受测试的代码。 view.QueryResultsGrid是一个System.Windows.Forms.DataGridView对象:

public void SelectCheckedChanged(object sender, EventArgs e)
{
    view.QueryResultsGrid.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
}

正在尝试测试:

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 Moq_Is_Hard()
{
    //Arrage
    DataGridView d = new DataGridView();
    mockWindow.SetupGet(x => x.QueryResultsGrid).Returns(d);

    //Act
    presenter.SelectCheckedChanged(null, null);

    //Assert
    //mockView.VerifyGet(x => x.QueryResultsGrid.SelectionMode, Times.AtMostOnce());
    mockWindow.VerifySet(x => x.QueryResultsGrid.SelectionMode, Times.AtMostOnce());
}

如果我在测试的代码行上放置断点,VS告诉我:属性或索引器'Presenter.IQueryForm.QueryResults'不能在此上下文中使用,因为它缺少get访问器。但是,在测试中,我以为我在模拟器上设置了Get访问器,所以我不明白这个消息。最后,NUnit给出:'对象引用未设置为对象的实例'。

非常感谢任何帮助!

安迪

1 个答案:

答案 0 :(得分:1)

您的代码正在做的是从模拟中获取DataGridView,然后在其上设置SelectionMode属性。 DataGridView的实际实现不受Mocks控制,因此它无法拦截SelectionMode的getter和setter。

其中一个问题(正如您可能已经发现的那样)是DataGridView实际上并不是Mockable,因此您必须返回实际的实现,存根任何属性并使用它。

以下测试通过我......

[Test]
public void SelectCheckedChanged_SetsModeToColumnHeaderSelect () {
    //Arrange
    //Mock the form to return a stubbed grid
    Mock<IQueryForm> form = new Mock<IQueryForm>();
    DataGridView grid = new DataGridView();
    grid.SelectionMode = DataGridViewSelectionMode.CellSelect;
    form.SetupGet(f => f.QueryResults).Returns(grid);
    QueryFormPresenter presenter = new QueryFormPresenter(form.Object);

    //Act
    presenter.SelectCheckedChanged();

    //Assert
    form.VerifyGet(f => f.QueryResults);
    Assert.AreEqual(DataGridViewSelectionMode.ColumnHeaderSelect, 
                    grid.SelectionMode);
}