1

您好我有以下问题。我试图模拟注入执行器的调用以立即执行给定的 Callable。稍后在 Callable 内部调用的方法的测试参数被捕获并断言参数。模拟示例见下文。

Maven 3,jdk 10-slim,mock 1.9

    //this task should be executed by executor
    private val taskCaptor = slot<Callable<Boolean>>()
    private val asyncTaskExecutor: LazyTraceThreadPoolTaskExecutor = mockk<LazyTraceThreadPoolTaskExecutor>().apply {
        //this was my 1st try, but resutt was java.lang.InstantiationError: java.util.concurrent.Callable
        //every { submit(capture(taskCaptor)) } returns CompletableFuture.completedFuture(taskCaptor.captured.call())
        //every { submit(any()) } returns CompletableFuture.completedFuture(true)
        every { submit(ofType(Callable::class)) } returns FutureTask<Boolean>(Callable { true })
    }

后来我将 Callable 接口更改为实现,这是我在测试类中创建的,但又遇到了另一个异常。与上述异常相同的代码是

java.lang.InstantiationError: java.util.concurrent.Future

这是submit方法的返回类型。

我嘲笑的方法是错误的吗?

4

1 回答 1

0

不确定这是否是最好的实现方式,但对我来说它是这样工作的:

    private val taskCaptor = slot<Callable<Boolean>>()
    private val asyncTaskExecutor: LazyTraceThreadPoolTaskExecutor = mockk<LazyTraceThreadPoolTaskExecutor>().apply {
        every { submit(ofType(Callable::class)) } returns mockFuture
        every { mockFuture.get() } returns true

    }

于 2020-08-27T13:13:25.817 回答