MockK模拟方法返回Interface Future

时间:2019-01-21 10:00:57

标签: kotlin mockk

你好,我有以下问题。 我正在尝试模拟注入执行程序的调用 立即执行给定的Callable。稍后在测试中,将调用Callable内部调用的方法的参数,并声明参数。模拟示例,请参见下面。

Maven 3,jdk 10-slim,mockk 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方法的返回类型。

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

1 个答案:

答案 0 :(得分: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

    }