简体   繁体   English

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

[英]Setting up Spek test for http methods using Kotlin?

How do I spin up a spek test using kotlin to test whether or not an HTTP method post has been called?如何使用 kotlin 启动 spek 测试以测试是否已调用 HTTP 方法帖子? Whats tripping me out is i'm having trouble mocking up the context.让我失望的是我在模拟上下文时遇到了麻烦。 I'd like to pass in a method other then HttpMethod.POST to fire off the else block.我想传入一个方法而不是 HttpMethod.POST 来触发 else 块。

Currently fails with the message -当前失败并显示消息 -

    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)

It also fails saying context.request can't be null它也没有说 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")
            }
        }
 }
}

test file:测试文件:


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


        }
    }
})

here's what helped me get it to pass -这就是帮助我通过它的原因 -

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

        }
    }

it passed the test after this在这之后它通过了测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM