I'm new to Dagger 2 and I'm working on using Dagger 2 for unit tests. I would like to test my presenter and mock some of the datasources(Server connection, SharedPreferences).
For the SharedPreferences I have SharedPreferencesComponent
in the main
folder and SharedPreferencesComponentFake
in the test/java
folder. The problem is that dagger can't generate DaggerSharedPreferencesComponentFake
therefore I can't inject SharedPreferencesFake
instead the SharedPreferences.
How can i set up so dagger will generate the DaggerSharedPreferencesFake class , or am I using dagger 2 in the wrong way
Asked
Active
Viewed 141 times
1

user1796624
- 3,665
- 7
- 38
- 65
-
Please try using the search function, since this seems like a question that has been asked before at least 3 times, e.g. http://stackoverflow.com/questions/36231457/dagger-not-generating-components-for-test-class – David Medenjak Jun 28 '16 at 11:13
1 Answers
0
Why not use Mockito and just mock the SharedPreferencesComponent
Mockito.when(SharedPreferencesComponent.yourMethod(any(String.class)))
.thenReturn(yourWanterOutput);
This will make faking classes unnecessary and the code will be cleaner.

loshkin
- 1,600
- 2
- 21
- 38
-
thats true, but i want to know is testing is better using dagger, i have already prepared fake clases – user1796624 Jun 28 '16 at 11:23
-
You use mocks and stubs in order to isolate behaviour. In this particular case, you don't want to test the shared preferences that is why you mock their behaviour so it is constant and not vital for the final result of the test. If you were about to test some real behaviour of the SharedPreferences then you can add them with the dagger. You can not say that dagger or mocking or stubbing is better for testing they all serve different purpose. – loshkin Jun 28 '16 at 11:34