0

I think I have some unit testing-dagger missed.

I am trying to test a class which implements this Interface:

public interface GetAndroidOSVersionInteractor {
    public String execute ();
}

The class is this one:

public class GetAndroidOSVersionInteractorImpl implements GetAndroidOSVersionInteractor {

    @Inject
    public GetAndroidOSVersionInteractorImpl (){
        super();
    }

    @Override
    public String execute() {
        String version = "android: " + Build.VERSION.RELEASE + " device: " + Build.MANUFACTURER + Build.MODEL;
        return(version);
    }
}

Its inject module is this one:

@Module(library = true, complete = false)
public class InteractorsModule {

    @Provides
        GetAndroidOSVersionInteractor provideGetAndroidOSVersionInteractor(GetAndroidOSVersionInteractorImpl getAndroidOSVersionInteractorImpl) {
            return getAndroidOSVersionInteractorImpl;
        }
}

But when I execute this test, it always return a -1 NullPointerException:

@RunWith(MockitoJUnitRunner.class)
public class GetAndroidOSVersionInteractorTest extends TestCase {

    GetAndroidOSVersionInteractor getAndroidOSVersionInteractor;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void executeTest(){
        final String os = getAndroidOSVersionInteractor.execute();
        assertNotNull(os);
    }

}

What am I missing? Is it a problem with Dagger 1.2? Could you explain me why this doesn't work?

Thank you very much.

Javier Sivianes
  • 784
  • 1
  • 9
  • 25

1 Answers1

0

You most likely need the following:

@RunWith(MockitoJUnitRunner.class)
public class GetAndroidOSVersionInteractorTest extends TestCase {
    @Inject // <-- this
    GetAndroidOSVersionInteractor getAndroidOSVersionInteractor;

and

private ObjectGraph testObjectGraph;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    testObjectGraph = ObjectGraph.create(new MockModule());
    testObjectGraph.inject(this);
}

and

@Module(injects={GetAndroidOSVersionInteractorTest.class}, includes={InteractorsModule.class})
public class MockModule {
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • I do not understand very well what MockModule does. I think that I need to inject manually my dependencies via ObjectGraph, but I am not sure what this class does. Please, correct me if I am wrong. Thx. – Javier Sivianes Jun 02 '15 at 15:17
  • You need to create a root module that includes your modules, and also specifies that it injects the test classes. For more information, check out my Dagger1 guide: http://stackoverflow.com/a/27036934/2413303 – EpicPandaForce Jun 02 '15 at 16:07