0
에스프레소 테스트에서 실행중인 DaggerMock의 구현을 성공적으로 시도하지 못했습니다. 샘플을 거의 정확하게 복사했지만 가상 구현이 아닌 MainPresenter
의 실제 구현을 항상 사용합니다.DaggerMock이 에스프레소 테스트에서 모의 객체를 주입하지 않음
EspressoRule은 (real world sample에서 정확하게 복사) :
public class EspressoDaggerMockRule extends DaggerMockRule<AppComponent>
{
public EspressoDaggerMockRule()
{
super(AppComponent.class, new AppModule(getApp()));
set(new ComponentSetter<AppComponent>()
{
@Override
public void setComponent(AppComponent appComponent)
{
getApp().setComponent(appComponent);
}
});
}
private static App getApp()
{
return (App) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
}
}
에스프레소 시험 :
public class MainActivityTest
{
@Rule
public EspressoDaggerMockRule rule = new EspressoDaggerMockRule();
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class, false, false);
@Mock MainPresenter presenter;
@Test
public void test() throws InterruptedException
{
final MainActivity activity = mActivityTestRule.launchActivity(null);
// presenter in this test class will be mocked but the presenter in activity will be real
Thread.sleep(1000);
}
}
MainActivity :
public class MainActivity extends BaseActivity implements MainContract.View
{
@Inject MainPresenter mainPresenter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void setupComponent(AppComponent appComponent)
{
appComponent
.mainActivityComponentBuilder()
.mainActivityModule(new MainModule(this))
.build()
.inject(this);
}
}
MainComponent :
,MainModule :
@Module
public class MainModule
{
private MainActivity mainActivity;
public MainModule(MainActivity mainActivity)
{
this.mainActivity = mainActivity;
}
@Provides
public MainContract.View mainView()
{
return mainActivity;
}
@Provides
public MainPresenter mainPresenter()
{
return new MainPresenter(mainActivity);
}
}
AppComponent
@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent
{
MainComponent.Builder mainActivityComponentBuilder();
}
응용 프로그램은 :
public class App extends Application
{
public static AppComponent appComponent;
@Override
public void onCreate()
{
super.onCreate();
setupGraph();
}
private void setupGraph()
{
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
public void setComponent(AppComponent component)
{
appComponent = component;
}
}
샘플은 잘 실행됩니다. 내가 놓친 게 있니?
내가 여기에 노력하고있어 전체 소스 코드를 업로드 한는 : https://github.com/jbmlaird/DaggerMockRepository