如何创建在responseWriter.Write 上返回错误的http.ResponseWriter 模拟实例?
来源:stackoverflow
2024-03-16 22:30:28
0浏览
收藏
在 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删除
解组字符串 json 时,在输入字节 0 处获取非法的 base64 数据
- 上一篇
- 解组字符串 json 时,在输入字节 0 处获取非法的 base64 数据
- 下一篇
- Java SVN 时光机器:穿越代码变更的维度
查看更多
最新文章
-
- Golang · Go问答 | 14分钟前 |
- Go HTTP 中间件重复写响应头的定位方法
- 270浏览 收藏
-
- Golang · Go问答 | 36分钟前 |
- Go ServeMux 路径变量冲突时的路由选择排查
- 350浏览 收藏
-
- Golang · Go问答 | 1小时前 | go · Go os/exec ErrWaitDelay WaitDelay
- Go exec.WaitDelay 为什么会返回 ErrWaitDelay
- 333浏览 收藏
-
- Golang · Go问答 | 1小时前 |
- Go url.URL 同时设置 Path 和 Opaque 为什么结果不同
- 170浏览 收藏
-
- Golang · Go问答 | 2小时前 | go ·
- Go url.ParseQuery 返回错误时为什么仍有部分 Values
- 311浏览 收藏
-
- Golang · Go问答 | 7小时前 | Go问答 · URL Go net/url RawPath EscapedPath
- Go url.RawPath 设置后为什么可能被 EscapedPath 忽略
- 370浏览 收藏
-
- Golang · Go问答 | 7小时前 | Go问答 · Go url.JoinPath PathEscape RawPath
- Go url.JoinPath 为什么会转义某些路径字符
- 140浏览 收藏
-
- Golang · Go问答 | 12小时前 |
- Go MaxBytesReader 超限后为什么还需要处理连接状态
- 399浏览 收藏
-
- Golang · Go问答 | 12小时前 |
- Go ResponseController Flush 为什么可能返回 ErrNotSupported
- 197浏览 收藏
-
- Golang · Go问答 | 12小时前 |
- Go multipart.FileHeader Filename 为什么不能直接拼接本地路径
- 412浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 254次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 298次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 272次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 251次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 58次使用
查看更多
相关文章
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览
-
- Go sql.Tx提交成功前读取结果导致事务边界混乱的修复方法
- 2026-09-20 501浏览
-
- Go select 用 time.After 做超时有什么资源代价
- 2026-09-10 501浏览
