I have the following LoginFragment that uses Dagger to inject its fields:
class LoginFragment : DaggerFragment() {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this, viewModelFactory)
.get(LoginViewModel::class.java)
}
I also have a corresponding test that mocks the LoginViewModel according to the documentation from Google: "You can create the fragment and provide it a mock ViewModel."
@MediumTest
@RunWith(AndroidJUnit4::class)
class LoginFragmentTest {
@Mock
private lateinit var viewModel: LoginViewModel
@Before
fun setUp() {
loginFragment = LoginFragment()
loginFragment.viewModelFactory = createMockViewModelFactory(viewModel)
activityRule.activity.setFragment(loginFragment)
}
}
The problem is that when the onAttached
method of the fragment is invoked, Dagger overrides the viewModelFactory
with its own object, thus replacing my mock.
How can I prevent Dagger from overriding my mock object?