问题描述
我很好奇人们喜欢使用哪种方法进行嘲笑,以及为什么.我知道的两种方法是使用硬编码的模拟对象和模拟框架.为了演示,我将使用C#概述一个示例.
I'm curious as to what method people like to use for mocking and why. The two methods that I know of are using hard coded mock objects and a mocking framework. To demonstrate, I'll outline an example using C#.
假设我们有一个IEmployeeRepository接口,其中有一个名为GetEmployeeById的方法.
Suppose we have an IEmployeeRepository interface with a method called GetEmployeeById.
public interface IEmployeeRepository
{
Employee GetEmployeeById(long id);
}
我们可以轻松地创建一个模拟:
We can easily create a mock of this:
public class MockEmployeeRepository : IEmployeeRepository
{
public Employee GetEmployeeById(long id)
{
Employee employee = new Employee();
employee.FirstName = "First";
employee.LastName = "Last";
...
return employee;
}
}
然后,在我们的测试中,我们可以通过setter或依赖项注入明确地告诉我们的服务使用MockEmployeeRepository.我是模拟框架的新手,所以我很好奇为什么我们可以使用它们,如果我们能做到上面的事情呢?
Then, in our tests we can explicitly tell our services to use the MockEmployeeRepository, either using a setter or dependency injection. I'm new to mocking frameworks so I'm curious as to why we use them, if we can just do the above?
推荐答案
那不是模拟,而是存根.对于存根,您的示例是完全可以接受的.
That's not a Mock, it's a Stub. For stubbing, your example is perfectly acceptable.
来自Martin Fowler:
From Martin Fowler:
模拟是我们在这里所说的:预先编程并带有期望的对象,这些对象构成了期望接收的呼叫的规范.
Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
在嘲笑某些东西时,通常会调用验证"方法.
When you're mocking something, you usually call a "Verify" method.
看一下这是Mocks和Stub之间的区别 http://martinfowler.com/articles/mocksArentStubs.html
Look at this for the diff between Mocks and Stubshttp://martinfowler.com/articles/mocksArentStubs.html
这篇关于硬编码模拟对象与模拟框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!