使用Moq和NUnit,什么是写入方法/更好的语法?

时间:2010-01-14 22:36:33

标签: c# unit-testing nunit installation moq

我正试图测试这种行为

- BLOGTableAdapter.GetBlogsByTitle(字符串    title)只召唤一次

- 用字符串调用    长度大于1,

- 它返回BLOGDataTable对象

 [Test]
    public void GetBlogsByBlogTitleTest4()
    {
        var mockAdapter = new Mock<BLOGTableAdapter>();
        var mockTable = new Mock<BLOGDataTable>();

        mockAdapter.Setup(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0))).Returns(mockTable.Object);

        var blogBl = new BlogManagerBLL(mockAdapter.Object);
        blogBl.GetBlogsByBlogTitle("Thanks for reading my question");

        mockAdapter.VerifyAll();
        mockAdapter.Verify(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0)), Times.Exactly(1));
    }

当调用GetBlogsByTitle(字符串标题)时,在课程中说Data Aceess Layer中的“BlogManagerBLL”

public BLOGDataTable GetBlogsByBlogTitle(string title)
        {
            return Adapter.GetBlogsByTitle(title);
        }

如您所见,我使用两个单独的语句来完成这些检查

mockAdapter.Setup(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0))).Returns(mockTable.Object);    
mockAdapter.Verify(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0)), Times.Exactly(1));
  1. 我怎么把它合二为一 声明?
  2. 我测试的是正确的吗?
  3. 由于

1 个答案:

答案 0 :(得分:5)

如果你正在测试两件事,你应该写两个测试。

[Test]
public void BlogTableAdapter_should_be_called_with_string_having_length_greater_than_1()
{
    var mockAdapter = new Mock<BLOGTableAdapter>();

    var blogBl = new BlogManagerBLL(mockAdapter.Object);
    blogBl.GetBlogsByBlogTitle("Thanks for reading my question");

    mockAdapter.Verify(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0)));
}

[Test]
public void BlogTableAdapter_should_return_a_BLOGDataTable_object()
{
    var mockAdapter = new Mock<BLOGTableAdapter>();
    mockAdapter.Setup(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0))).Returns(new BLOGDataTable());

    var blogBl = new BlogManagerBLL(mockAdapter.Object);
    var returnValue = blogBl.GetBlogsByBlogTitle("Thanks for reading my question");

    Assert.That(returnValue, Is.TypeOf(typeof(BLOGDataTable)));
}

所以我想我的建议是不要把它们放在一起,为每个人创建一个测试。而且我会说你正在测试正确的东西。