lundi 17 février 2020

Provide all dependencies for complicated class with Mockito

Senario

I am going to Test my activity with AndroidUnittest and Mockito. I have two classes that wanna mock with Mockito. ( realy i do not care inside these two class i just wanna mock them and see activity interactions with them) One is viewModel and other is SomeManager. Both have complicated dependencies that finally needs context which all dependencies provided by dagger. Some of them has module and some of them has constructor injection. I just share my ViewModel and if i can find a solution it will also works for my Manager.

class HomeActivityViewModel @Inject
internal constructor(
    @Named("io") val dispatcher: CoroutineDispatcher,
    private val navigationDrawerManager: NavigationDrawerManager,
    private val userAccountManager: UserAccountManager, //Needs context
    private val tokenManager: TokenManager, //Needs context
    private val context: Context,
    private val authRepository: AuthRepository,  //It is a interface that Impl provided by dagger
    private val retrofit: Retrofit,
    private val userInformationRepository: UserInformationRepository
) : ObservableViewModel(), CoroutineScope {

And this is in test class:

@InjectMocks
lateinit var mockViewModel: HomeActivityViewModel

//All needed in viewModel
@InjectMocks
lateinit var navigationDrawerManager: NavigationDrawerManager
@InjectMocks
lateinit var userAccountManager: UserAccountManager
@InjectMocks
lateinit var tokenManager: TokenManager
@Mock
lateinit var authRepository: AuthRepository 
...

@Before
fun setup() {
    MockitoAnnotations.initMocks(this)
}

Problems

  1. How to provide Context

I provided all complicated objects ( My viewModel and Manager) by @InjectMocks and simple dependencies by @Mock But at end i need Context that i think it can not provide by Mockito. So i do not know how i can provide context for that @Mock annotations. I just put

val context: Context = InstrumentationRegistry.getInstrumentation().context

but do not know how i can expose this to Mockito wire ups in

  1. How to expose some custom mock objects to @Mock or @InjectMocks annotated objects

Also some of classes can not mocked like: Retrofit. So i have to create a mock and pass to that object that needs as dependencies. (Annotated by @Mock or @InectMocks) But i do not know how?! For example if i prepare Retrofit like this:

var okHttpClient = OkHttpClient()
var retrofit: Retrofit = RetrofitBuilderFactory.createRetrofit(okHttpClient)

How i can expose them to consumed by @Mock or @InjectMock items?

Aucun commentaire:

Enregistrer un commentaire