模拟一个类与模拟它的接口 [英] Mocking a class vs. mocking its interface

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

问题描述

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

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

对比

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.

此外,mocking 框架在mocking 类方面有局限性,有些框架默认只模拟接口.

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

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

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