嘲笑一个类与嘲弄它的界面 [英] Mocking a class vs. mocking its interface

查看:143
本文介绍了嘲笑一个类与嘲弄它的界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于单元测试,我需要模拟几个依赖项。其中一个依赖项是实现接口的类:

For a unit test, I need to mock several dependencies. One of the dependencies is a class which implements an interface:

public class DataAccessImpl implements DataAccess {
    ...
}

我需要设置这个类的模拟对象,当返回一些指定的值时提供了一些指定的参数。

I need to set up a mock object of this class which returns some specified values when provided with some specified parameters.

现在,我不确定,是否更好地模拟接口或类,即

Now, what I'm not sure of, is if it's better to mock the interface or the class, i.e.

DataAccess client = mock(DataAccess.class);

vs。

DataAccess client = mock(DataAccessImpl.class);

在测试方面有什么不同吗?什么是首选方法?

Does it make any difference in regard to testing? What would be the preferred approach?

推荐答案

在您的情况下可能没有太大区别,但首选的方法是模拟界面,通常如果您遵循TDD(测试驱动开发),那么您甚至可以在编写实现类之前编写单元测试。因此,即使您没有具体的类 DataAccessImpl ,您仍然可以使用您的接口 DataAccess 编写单元测试。

It may not make much difference in your case but the preferred approach is to mock interface, as normally if you follow TDD (Test Driven Development) then you could write your unit tests even before you write your implementation classes. Thus even if you did not have concrete class DataAccessImpl, you could still write unit tests using your interface DataAccess.

此外,模拟框架在模拟类中有局限性,而某些框架默认只模拟接口。

Moreover mocking frameworks have limitations in mocking classes, and some frameworks only mock interfaces by default.

这篇关于嘲笑一个类与嘲弄它的界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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