I am working on an Android library and I am writing an instrumented test for it using UI Automator and Mockk.
The library has a class called InstallManager which will install stuff on the device. I want the InstallManager to throw an exception so that I can test if an error notification will be shown.
All I do is finding the Update (Install) button and click on it
val updateButtonComponent = device.findObject(By.text(updateButtonText))
updateButtonComponent.click()
How can I mock/manipulate the InstallManager which is being used by the library during the automated test?
What I tried:
I tried mocking the InstallManager before running the automated test, hoping that UI Automator would magically know that it should use this mocked InstallManager. But (as I thought already) it does not work like that...
private fun breakInstallManager() {
installManager = spyk(InstallManager(mockk(relaxed = true), nonExistentFile))
every { installManager.getString(any()) } returns ""
every { installManager.packageName } returns ""
}
CodePudding user response:
For mocking InstallManager class in android tests, call MockKAnnotations.init
method. Then in the test method you can specify the return value
@RelaxedMockK
private lateinit var installManager: InstallManager
@Before
fun setUp() {
MockKAnnotations.init(this)
// …
}
@Test
fun installManagerTest(){
every { installManager.getString(any()) } returns ""
every { installManager.packageName } returns ""
// …
}