我刚开始使用 Rhino mock 为我的项目设置测试用例。 .Return(objToReturn:list) 究竟做了什么?
它似乎只有在我初始化并填充列表然后将其传递给模拟 stub 方法时才有效。我假设我可以使用 Mock Stub 方法来填充列表然后返回该填充列表。
....
private ProductRepository _productRepository;
private IProductRepository _productRepositoryStub;
[SetUp]
public void SetUp()
{
_productRepository = new ProductRepository();
//Testing using Rhino Mocks
//Generate stub
_productRepositoryStub = MockRepository.GenerateMock<IProductRepository>();
}
[Test]
public void Canquerydb()
{
IList list = _productRepository.GetAllProducts();
_productRepository.Stub(x=> x.GetAllProducts()).Return(list);
_productRepositoryStub.AssertWasCalled(x => x.GetAllProducts());
}
/// <summary>
/// Refaactor and use MockRhino here
/// </summary>
[Test]
public void can_insert_product()
{
IProduct product = new Grains("Cheese Bread", "Dairy grain", 0);
_productRepository.SaveProduct(product);
_productRepositoryStub.Stub(x=>x.SaveProduct(product));
_productRepositoryStub.AssertWasCalled(x => x.SaveProduct(product));
}
最佳答案
回答您的问题标题:Rhino 模拟区分模拟和 stub 。 Mock 是唯一可以使测试失败的东西,因为它是您正在测试的东西的包装实例 - 您的被测系统 (SUT)。您在 Rhino 模拟中“ stub ”一些东西,以便您可以满足模拟对象的依赖关系。 stub 让您可以看到传递给它的参数,并让您可以控制返回结果,以便您可以完全隔离地对 Mock 的行为做出断言。
本网站还有更多explanation of Mocks and Stubs .
要添加,像Moq 这样的库不要区分模拟和 stub 。通过使用泛型,您不必模拟您的 SUT。我个人更喜欢 Moq 的这种简单性。
关于c# - 为什么要使用 Rhino Mock Stub 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14571943/