I wanted to ask what’s the general rule of mocking field injected classes in the activity?
For example, let’s say I have a view model injected in my activity. Let’s assume it’s not VM from architecture component library, but our custom class (which uses constructor injection). When running the Espresso test, I don’t want to inject the actual class and it’s dependencies, but I’d rather want to provide the mocked VM.
Below are some code snippets
MainActivity:
class MainActivity : AppCompatActivity() {
@Inject
internal lateinit var viewModel: MainActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
DaggerMainActivityComponent.factory()
.create(this)
.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
MainActivityViewModel:
@Mockable
class MainActivityViewModel @Inject constructor(
private val repo: MainActivityRepo
) {
...
}
MainActivityTest:
class MainActivityTest {
@get:Rule
val activityRule = IntentsTestRule(
MainActivity::class.java,
false,
true
)
private val mainActivityViewModel = mock<MainActivityViewModel>()
@Before
fun setup() {
activityRule.activity.viewModel = mainActivityViewModel
}
fun someMocking() {
whenever(mainActivityViewModel...)
.thenReturn(...)
}
}
It’d be great if somebody can give a feedback on it, or maybe suggest the better implementation. Thanks.
Tags: androidandroid, class, exception