Mario Adam
05/19/2023, 9:38 AMclass Client(private val context: Context) {
fun sendCommandString(command: String, parameter: String) {
val intent = Intent()
intent.action = Intents.ACTION_DATAWEDGE
intent.putExtra(command, parameter)
intent.putExtra(Intents.EXTRA_SEND_RESULT, "true")
context.sendBroadcast(intent)
}
}
and this is my test:
class ClientTest : MockkUnitTest() {
@RelaxedMockK
lateinit var context: Context
@Test
fun verifySendCommandString() = runTest {
// Arrange
every { context.sendBroadcast(any()) } returns Unit
val client = Client(context)
// Act
client.sendCommandString("some command", "some parameter")
// Assert
verify(exactly = 1) {
context.sendBroadcast(withArg {
Truth.assertThat(it.action).isEqualTo(Intents.ACTION_DATAWEDGE)
Truth.assertThat(it.extras).isNotNull()
Truth.assertThat(it.extras!!.containsKey("some command")).isTrue()
Truth.assertThat(it.getStringExtra("some command")).isEqualTo("some parameter")
Truth.assertThat(it.extras!!.containsKey(Intents.EXTRA_SEND_RESULT)).isTrue()
Truth.assertThat(it.getStringExtra(Intents.EXTRA_SEND_RESULT)).isEqualTo("true")
})
}
}
}
The error is: Method setAction in android.content.Intent not mocked.
. Well - I know. There should be no need to mock this method. I only have mocked the context to ensure, a correct intent
has been created.
(also posted on StackOverflow: https://stackoverflow.com/questions/76287781/test-complains-about-unmocked-method)ephemient
05/19/2023, 9:46 AMMario Adam
05/19/2023, 9:47 AMtestOptions {
unitTests.returnDefaultValues = true
}
This at least causes the test to not complain as mentioned aboveephemient
05/19/2023, 9:48 AMandroid.jar
with a modified stub whose methods don't throw, but do nothing insteadMario Adam
05/19/2023, 9:49 AMIntent()
to result in null
ephemient
05/19/2023, 9:50 AMephemient
05/19/2023, 9:50 AMMario Adam
05/19/2023, 9:51 AMMario Adam
05/19/2023, 9:51 AMbut for the most part, if code touches an Android API, I’d consider it no longer a unit testOK - I understand
ephemient
05/19/2023, 9:51 AMephemient
05/19/2023, 9:52 AMMario Adam
05/19/2023, 10:13 AMtestOptions
block from above (docs say to use it as a last resort) and converted the test to a robolectric test… works fine now… I will put the result as an answer on StackOverflow