gpt4 book ai didi

c# - 使用 Moq 和 NUnit ,什么是编写方法/更好的语法?

转载 作者:太空宇宙 更新时间:2023-11-03 20:42:13 24 4
gpt4 key购买 nike

我正在尝试测试这种行为

-- 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(string title) 时,在类中说数据访问层中的“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. 我测试的东西是否正确?

谢谢

最佳答案

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

[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)));
}

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

关于c# - 使用 Moq 和 NUnit ,什么是编写方法/更好的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2068066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com