gpt4 book ai didi

android - 使用 Dagger 2 在单元测试中进行字段注入(inject)

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:14:45 24 4
gpt4 key购买 nike

根据 Dagger documentation 中的建议,对于单元测试,我们根本不需要涉及 Dagger,对于提供的示例,它是有意义的:

class ThingDoer {
private final ThingGetter getter;
private final ThingPutter putter;

@Inject ThingDoer(ThingGetter getter, ThingPutter putter) {
this.getter = getter;
this.putter = putter;
}

String doTheThing(int howManyTimes) { /* … */ }
}

有了这个类结构,单元测试很简单,只需模拟 getterputter,将它们作为构造函数参数传递,指示 mockito 在与任何交互时返回什么这些对象,然后对 doTheThing(...) 进行断言。

当我必须对结构类似于此的类进行单元测试时,我在测试中遇到困难:

class ThingDoer {
@Inject
ThingGetter getter;

@Inject
ThingPutter putter;

@Inject
ThingMaker maker;

@Inject
// other 10 objects

public ThingDoer() {
App.getThingComponent().inject(this);
}

String doTheThing(int howManyTimes) { /* … */ }
}

如您所见,我不再使用构造函数注入(inject),而是使用字段注入(inject)。主要原因是构造函数中没有太多的参数。

ThingDoer 的所有依赖项都使用字段注入(inject)提供时,有没有办法在 ThingDoer 中注入(inject)模拟依赖项?

最佳答案

对于字段注入(inject),您可以创建一个组件和一个模块用于单元测试。

假设你有单元测试类 ThingDoerTest,你可以让组件将依赖项注入(inject) ThingDoerTest 而不是 ThingDoer 并且模块提供模拟对象而不是真实对象。

在我的项目中,HomeActivity有一个字段注入(inject)HomePresenter。以下代码是一些 fragment 。希望代码可以给你一些想法。

@RunWith(AndroidJUnit4.class)
public class HomeActivityTest implements ActivityLifecycleInjector<HomeActivity>{

@Rule
public InjectorActivityTestRule<HomeActivity> activityTestRule = new InjectorActivityTestRule<>(HomeActivity.class, this);

@Inject
public HomePresenter mockHomePresenter;

@Override
public void beforeOnCreate(HomeActivity homeActivity) {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
MyApplication myApplication = (MyApplication) instrumentation.getTargetContext().getApplicationContext();

TestHomeComponent testHomeComponent = DaggerHomeActivityTest_TestHomeComponent.builder()
.appComponent(myApplication.getAppComponent())
.mockHomeModule(new MockHomeModule())
.build();
testHomeComponent.inject(HomeActivityTest.this);
homeActivity.setHomeComponent(testHomeComponent);
}

@Test
public void testOnCreate() throws Exception {
verify(mockHomePresenter).start();
}

@ActivityScope
@Component(
dependencies = {
AppComponent.class
},
modules = {
MockHomeModule.class
}
)
public interface TestHomeComponent extends HomeComponent {
void inject(HomeActivityTest homeActivityTest);
}

@Module
public class MockHomeModule {
@ActivityScope
@Provides
public HomePresenter provideHomePresenter() {
return mock(HomePresenter.class);
}
}

}

关于android - 使用 Dagger 2 在单元测试中进行字段注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41485191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com