Ilya Gazman
Ilya Gazman

Reputation: 32271

How to mock injected objects with Hilt?

Consider the below example

@Singleton
class LoginModel @Inject contractor(private val userModel:UserModel){

}

@Config(application = HiltTestApplication::class)
@HiltAndroidTest
class LoginModelTest {

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @Inject
    lateinit var loginModel: LoginModel

    @Before
    open fun setup() {
        hiltRule.inject()
    }
}

How to mock UserModel inside the LoginModel without manually constructing LoginModel?

Upvotes: 5

Views: 4735

Answers (2)

Ilya Gazman
Ilya Gazman

Reputation: 32271

Thanks, Jakub for the link. Here is my favorite way of doing it

@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {

  @BindValue @JvmField
  val analyticsService: AnalyticsService = FakeAnalyticsService()

  ...
}

Upvotes: 0

Jakub Pruszyński
Jakub Pruszyński

Reputation: 794

The solution is simple. You have to deliver two different versions of UserModel - production, and mock in tests. You can do it by following these steps.

  1. Provide UserModel thru hilt module, annotating by Inject is not enough
  2. Accordingly to your needs :

Replace that module just in single test sheet https://developer.android.com/training/dependency-injection/hilt-testing#replace-binding-manually

Or

Replace in all tests https://developer.android.com/training/dependency-injection/hilt-testing#replace-binding

In both cases you will end up with module which return mock in binding.

Cheers

Upvotes: 4

Related Questions