如何使用 Mockito 模拟意图?

Mar*_*. F 5 junit mockito android-intent android-studio mockk

我试图在我所做的函数中模拟意图。这是下面的函数

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())
}
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试文件

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

并且不要忘记我用于测试的依赖项,希望它具有正确的版本。我认为我不必显示任何与测试文件无关的依赖关系或任何设置。

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'
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,它导致了这样的错误

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)
Run Code Online (Sandbox Code Playgroud)

我什至尝试模拟every仅使用 Intent::class.java 访问Intent("test")这样的代码every { Intent("aa") } returns mockIntent。但它仍然导致错误。