lundi 12 septembre 2016

Unit testing while using Dagger 2 (Robolectric and Mockito)

I'm trying to write some tests for fragments which have fields annotated with @Inject. For example, a chunk of my app looks like this:

Module:

@Module
public class PdfFactoryModule {

    @Provides @Singleton
    PdfFactory providePdfFactory() {
        return PdfFactory.getPdfFactory();
    }
}

Component:

@Singleton
@Component(modules = PdfFactoryModule.class)
public interface CorePdfComponent {
    void inject(PagerFragment pagerFragment);
}

Application:

public class CorePdfApplication extends Application {
    @NonNull
    private CorePdfComponent component;

    @Override
    public void onCreate() {
        super.onCreate();
        component = DaggerCorePdfComponent.builder().build();
    }

    @NonNull
    public CorePdfComponent getComponent() {
        return component;
    }

}

PagerFragment:

public class PagerFragment extends Fragment {
@Inject PdfFactory pdfFactory;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Dagger 2
    ((CorePdfApplication) getActivity().getApplication()).getComponent().inject(this);
}

(Note that these are only snippets of my whole code, I'm showing only the essentials for this particular dependency to keep it clear.)


I was trying to do a test like this:

Fake Module:

@Module
public class FakePdfFactoryModule extends PdfFactoryModule {

    @Override
    PdfFactory providePdfFactory() {
        return Mockito.mock(PdfFactory.class);
    }
}

Fake Component:

@Singleton
@Component(modules = FakePdfFactoryModule.class)
public interface FakeCorePdfComponent extends CorePdfComponent {
    void inject(PagerFragmentTest pagerFragmentTest);
}

Fake Application:

public class FakeCorePdfApplication extends CorePdfApplication {
    @NonNull
    private FakeCorePdfComponent component;

    @Override
    public void onCreate() {
        super.onCreate();
        component = DaggerFakeCorePdfComponent.builder().build();
    }

    @NonNull
    public FakeCorePdfComponent getComponent() {
        return component;
    }
}

Test:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, application = FakeCorePdfApplication.class)
public class PagerFragmentTest {

    PagerFragment pagerFragment;

    @Before
    public void setup() {
        pagerFragment = new PagerFragment();
        startVisibleFragment(pagerFragment);
    }

    @Test
    public void exists() throws Exception {
        assertNotNull(pagerFragment);
    }

But the DaggerFakeCorePdfComponent doesn't generate. I may have messed up big time because I never tested with dependency injection. What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire