Dagger2 + Mockito:如何对该场景进行单元测试? [英] Dagger2 + Mockito: How to Unit Test this scenario?

查看:190
本文介绍了Dagger2 + Mockito:如何对该场景进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个团队项目中,该项目具有非常好的代码。我正在尝试增加单元测试的覆盖范围,并且遇到了以下情况:

I'm working on a team project which has a very coupled code. I'm trying to increase the unit test coverage and I've faced the following scenario:

class Foo {
    static void methodA () {
        Bar b = new Bar();
        b.getContent();
    }
}

class Bar {

    @Inject
    DBAcessor mDBAcessor;

    Bar () {
        Dagger2.getInjector().inject(this);
    }

    public Object getContent() {
        mDBAcessor.fetchData();
    }

}

我要进行单元测试 methodA(),但是我不知道是否可以通过构造函数将 DBAcessor 对象传递给 Bar()类。 Bar 应该是在整个项目中广泛使用的POJO模型,因此,我不知道更改其构造函数并影响这么多其他类是否是一个好主意。关于如何应对这种情况的任何提示?

I want to unit test methodA(), however I don't know if it is possible to do it without passing the DBAcessor object via constructor to Bar() class. Bar should be a POJO model being widely used throughout the project, hence, I don't know if it would be a good idea to change its constructor and impact so many other classes. Any tips on how should I approach this scenario?

推荐答案

那是错误的设计。

只要您有权访问构造函数,就将类依赖关系传递给构造函数。这确实简化了单元测试。 Class Bar 应该看起来是:

Whenever you have an access to the constructor, pass class dependencies into constructor. That really eases unit testing. Class Bar should look:

class Bar() {

    @Inject DBAcessor mDBAcessor;

    Bar (DBAcessor dbAcessor) {
        this.mDBAcessor = dbAcessor;
    }

    public Object getContent() {
        mDBAcessor.fetchData();
    }
}

Dagger2 Component 仅应在无法访问构造函数( Activity Fragment )。

然后没有什么可以阻止您这样做:

Then nothing prevents you from doing that:

DBAccessor dbAccessor = Mockito.mock(DBAccessor.class);
Bar bar = new Bar(dbAccessor);
bar.getContent();
verify(bar, times(1)).fetchData();

如果您确实需要坚持这样的设计,那么您就不能对该对象进行单元测试,因为 Dagger2 取决于 Application 对象,该对象需要 Context ,您无法在单元测试中进行仿真。将测试写为 androidTest ,创建适当的 Activity ,获取 Bar 从中进行测试。

If you really need to stick to such design, then you can't make unit tests on such object, as Dagger2 depends on Application object, which needs Context, which you cannot emulate in unit tests. Write your test as androidTest, create appropriate Activity, fetch Bar object from it and test it.

这篇关于Dagger2 + Mockito:如何对该场景进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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