I am attempting to mock intent inside the function I made. Here is the function below
fun learningUnitTest(context: Context) {
val str = context.getString(R.string.app_name)
val intent = Intent(context, TodoFragment::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
} // it resulting null. how to mock this?
val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
Log.d("AA", str)
Log.d("BB", pendingIntent.toString())
}
And this is my unit test file
import android.content.Context
import android.content.Intent
import android.util.Log
import com.example.todoapp.controller.worker.learningUnitTest
import io.mockk.*
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.*
class ExampleUnitTest {
private val FAKE_STRING = "FAKE"
@Mock
private lateinit var mockContext: Context
@Test
fun test_function() {
mockkStatic(Log::class)
mockkStatic(Intent::class)
mockContext = mock(Context::class.java)
every { Log.d(any(), any()) } returns 0
`when`(mockContext.getString(R.string.app_name))
.thenReturn(FAKE_STRING)
// every { Intent("aa") } returns mockIntent // Missing mocked calls inside every { ... }
learningUnitTest(mockContext)
verify(mockContext, times(1)).getString(R.string.app_name)
}
}
And not forgetting the dependencies which I used for testing, hopefully it has the correct version. I don't think I have to show any depedencies or any setup which are not related to the test file.
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
// Optional -- Mockito framework
testImplementation 'org.mockito:mockito-core:1.10.19'
testImplementation 'io.mockk:mockk:1.12.2'
testImplementation 'org.mockito:mockito-inline:3.8.0'
When I ran the test, it resulting an error like this
Method setFlags in android.content.Intent not mocked. See http://g.co/androidstudio/not-mocked for details.
java.lang.RuntimeException: Method setFlags in android.content.Intent not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.content.Intent.setFlags(Intent.java)
at com.example.todoapp.controller.worker.WorkerUtilsKt.learningUnitTest(WorkerUtils.kt:97)
at com.example.todoapp.ExampleUnitTest.test_function(ExampleUnitTest.kt:35)
I even tried to mock using every
for only the Intent::class.java accessing Intent("test")
for the code like this every { Intent("aa") } returns mockIntent
. But it still resulting an error.