使用Dagger为Espresso测试注入模拟

时间:2017-11-22 12:36:45

标签: java android android-espresso dagger-2

我尝试修改此repo的代码:Chiuki's android test 所以它适合我的项目的Dagger配置。

所以我做的是:

1)为Component添加MainActivity

@PerActivity
@Component(dependencies = DemoApplication.ApplicationComponent.class)
public interface MainActivityComponent {

void inject(MainActivity mainActivity);

Clock getClock();

}

2)修改Application课程以创建并提供ApplicationComponent

private ApplicationComponent component;

@Override
public void onCreate() {
    super.onCreate();
    component = createComponent();
    component.inject(this);
}

protected ApplicationComponent createComponent() {
return DaggerDemoApplication_ApplicationComponent.builder().build();
}

public ApplicationComponent component() {
return component;
}

3)在MainActivity的{​​{1}}:

中进行注射
onCreate()

我可以通过运行应用程序验证它似乎正在运行。

现在我正在尝试相应修改DaggerMainActivityComponent.builder() .applicationComponent(((DemoApplication) getApplication()).component()) .build() .inject(this); 文件夹中的测试 他们会继续工作。

第一步是更改androidTest内的createComponent()方法以提供模拟MockDemoApplication实例:

Clock

第二步是在@Override protected ApplicationComponent createComponent() { return DaggerDemoApplication_ApplicationComponent.builder() .clockModule(new ClockModule() { @Override Clock provideClock() { return Mockito.mock(Clock.class); } }) .build(); } 方法MainActivityTest内进行注射:

setUp()

所以现在我正在运行下一个测试,但它失败了@Before public void setUp() { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); DemoApplication app = (DemoApplication) instrumentation.getTargetContext().getApplicationContext(); DaggerMainActivityTest_TestComponent.builder() .mockClockModule(new MockClockModule()) .build() .inject(this); }

AssertionFailedError

我猜测注入工作正常,因为当调用时钟实例时测试没有Caused by: junit.framework.AssertionFailedError: 'with text: is "2008-09-23"' doesn't match the selected view. Expected: with text: is "2008-09-23" Got: "TextView{id=2131165184, res-name=date, visibility=VISIBLE, width=272, height=135, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=2017-11-22, input-type=0, ime-target=false, has-links=false}" 崩溃,但不知怎的,它正在返回

0 个答案:

没有答案