如何使用 kotlin 启动 spek 测试来测试是否调用了 HTTP 方法 post?让我失望的是我在模拟上下文时遇到了麻烦。我想传入 HttpMethod.POST 以外的方法来触发 else 块。
当前失败并显示消息-
handlers.AHandlerTest > initializationError FAILED
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class ...handlers.AHandler
Mockito cannot mock/spy because :
- final class
at handlers.AHandlerTest$1.invoke(AHandlerTest.kt:76)
at handlers.AHandlerTest$1.invoke(AHandlerTest.kt:17)
它也失败说 context.request 不能为空
import ratpack.handling.Context
class AHandler : Handler {
override fun handle(contex: Context) {
when (contex.request.method) {
HttpMethod.POST -> create(contex)
else -> {
contex.response.status(405)
contex.render("Unsupported method. Supported methods are: POST")
}
}
}
}
测试文件:
package handlers
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import handlers.AHandler
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import ratpack.handling.Context
import org.mockito.Mockito
import ratpack.http.HttpMethod
import kotlin.test.assertEquals
import kotlin.test.assertFails
class AHandlerTest: Spek({
val context = mock<Context>()
val httpReq = mock<Context> {
on { context.request.method }.doReturn(HttpMethod.DELETE)
}
describe("testing handler function") {
it("it should fail when not given a post method") {
}
}
})