登录
首页 >  Golang >  Go问答

如何创建在responseWriter.Write 上返回错误的http.ResponseWriter 模拟实例?

来源:stackoverflow

时间:2024-03-16 22:30:28 483浏览 收藏

在 Go 中,你可以通过创建一个实现 `http.ResponseWriter` 接口的模拟实例来模拟 `responseWriter.Write` 返回错误的情况。此模拟实例应实现 `Write` 方法,使其始终返回一个错误,例如 `fmt.Errorf("always errors")`。通过使用此模拟实例,你可以测试当 `responseWriter.Write` 失败时,响应正文是否为空。

问题内容

我将所有与响应相关的 go 代码移至一个函数中

import (
    "encoding/json"
    "net/http"

    "github.com/rs/zerolog"
)

func writeresponse(responsewriter http.responsewriter, responsebody any, httpstatuscode int) {
    encodedresponsebody, err := json.marshal(responsebody)

    if err != nil {
        // call logger

        apiresponse := newerrorapiresponse() // create a struct for http 500 responses
        encodedresponsebody, err = json.marshal(apiresponse)

        responsewriter.writeheader(http.statusinternalservererror)

        if err != nil {
            // call logger

            return
        }

        _, err = responsewriter.write(encodedresponsebody)

        if err != nil {
            // call logger
        }

        return
    }

    responsewriter.writeheader(httpstatuscode)
    _, err = responsewriter.write(encodedresponsebody)

    if err != nil {
        // call logger
    }
}

并为以下情况创建了测试

  • 成功
  • 错误 => json.marshal() 失败,但 responsewriter.write() 失败

现在我还想为以下情况创建一个测试

json.marshal() 失败,它尝试创建错误响应,但 responsewriter.write() 也尝试创建错误响应,因此我们只能记录错误

所以基本上我是从

开始的
import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestWriteResponse_NoResponseBody(testing *testing.T) {
    // TODO replace with mock returning error on .Write()
    responseWriter := httptest.NewRecorder()
    responseBody := make(chan int)

    WriteResponse(responseWriter, responseBody, http.StatusOK)

    assert.Equal(testing, http.StatusInternalServerError, responseWriter.Code, fmt.Sprintf("Expected status code %d, but got %d", http.StatusInternalServerError, responseWriter.Code))

    actualResponseBodyAsString := responseWriter.Body.String()

    assert.Equal(testing, "", actualResponseBodyAsString, fmt.Sprintf("Expected response body to be empty but got '%s'", actualResponseBodyAsString))
}

但是测试失败,因为 responsewriter.write() 工作正常。如何强制它返回错误以使响应正文为空?


正确答案


只需实现接口:

type responsewriter interface {
    header() header
    write([]byte) (int, error)
    writeheader(statuscode int)
}

所以类似

type ErrorMockResponseWriter struct {
    Body io.ReadCloser
    Code int
}

func (e *ErrorMockResponseWriter) Header() http.Header {
    return http.Header{}
}

func (e *ErrorMockResponseWriter) Write(data []byte) (int, error){
    e.Body = io.NopCloser(bytes.NewReader(data)) 
    return 0, fmt.Errorf("always errors")
}

func (e *ErrorMockResponseWriter) WriteHeader(statusCode int) {
    e.Code = statusCode
}

func TestWriteResponse_NoResponseBody(testing *testing.T) {
    // TODO replace with mock returning error on .Write()
    responseWriter := ErrorMockResponseWriter()
    responseBody := make(chan int)

    WriteResponse(responseWriter, responseBody, http.StatusOK)

    assert.Equal(testing, http.StatusInternalServerError, responseWriter.Code, fmt.Sprintf("Expected status code %d, but got %d", http.StatusInternalServerError, responseWriter.Code))

    actualResponseBodyAsString := responseWriter.Body.String()

    assert.Equal(testing, "", actualResponseBodyAsString, fmt.Sprintf("Expected response body to be empty but got '%s'", actualResponseBodyAsString))
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何创建在responseWriter.Write 上返回错误的http.ResponseWriter 模拟实例?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>