硬编码的模拟对象与模拟框架 [英] Hard-Coded Mock Objects vs Mocking Framework

查看:16
本文介绍了硬编码的模拟对象与模拟框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇人们喜欢用什么方法来模拟以及为什么.我知道的两种方法是使用硬编码的模拟对象和模拟框架.为了演示,我将概述一个使用 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#.

假设我们有一个带有 GetEmployeeById 方法的 IEmployeeRepository 接口.

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

然后,在我们的测试中,我们可以明确地告诉我们的服务使用 MockEmployeeRepository,无论是使用 setter 还是依赖注入.我是模拟框架的新手,所以我很好奇我们为什么要使用它们,如果我们可以做到以上几点?

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?

推荐答案

这不是 Mock,而是 Stub.对于存根,您的示例是完全可以接受的.

That's not a Mock, it's a Stub. For stubbing, your example is perfectly acceptable.

来自马丁·福勒:

Mocks 是我们在此讨论的内容:预编程了期望的对象,这些期望形成了它们期望接收的调用的规范.

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 和 Stubs 之间的区别http://martinfowler.com/articles/mocksArentStubs.html

Look at this for the diff between Mocks and Stubs http://martinfowler.com/articles/mocksArentStubs.html

这篇关于硬编码的模拟对象与模拟框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆