为什么要使用犀牛模拟存根方法
本文关键字:模拟 存根 方法 犀牛 为什么 | 更新日期: 2023-09-27 17:56:19
我刚刚开始使用 Rhino mock 为我的项目设置测试用例。究竟是什么.Return(objToReturn:list) do ?
它似乎只有在我初始化并填充列表然后将其传递给模拟存根方法时才有效。我假设我可以使用 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 mocks 区分了 Mocks 和 Stubs。模拟是唯一可以使测试失败的东西,因为它是你正在测试的东西的包装实例 - 你的被测系统(SUT)。你在 Rhino 模拟中"存根"一些东西,这样你就可以满足你的模拟对象的依赖关系。存根让您了解传递给它的参数,并让您控制返回结果,以便您可以完全隔离地断言 Mock 的行为。
这个网站有进一步的解释模拟和存根。
补充一点,像 Moq 这样的库不会区分模拟和存根。通过使用泛型,您不必模拟您的 SUT。我个人更喜欢这种简单的最小起订量。