gpt4 book ai didi

testing - 使用 Kotlin 为 http 方法设置 Spek 测试?

转载 作者:行者123 更新时间:2023-11-28 21:35:32 26 4
gpt4 key购买 nike

如何使用 kotlin 启动 spek 测试以测试是否已调用 HTTP 方法 post?让我失望的是我在模拟上下文时遇到了麻烦。我想传入 HttpMethod.POST 以外的方法来触发 else block 。

当前失败并显示消息 -

    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 can't be null

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") {


}
}
})

最佳答案

这是帮助我让它通过的原因 -

describe("testing handle function") {
it("it should fail when not given a post method") {
val aHandler = AHandler();
val result = RequestFixture.handle(aHandler, Action {request ->
request.method("DELETE")
})
result.status.code shouldEqual 405

}
}

测试通过

关于testing - 使用 Kotlin 为 http 方法设置 Spek 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59201858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com