为了账号安全,请及时绑定邮箱和手机立即绑定

模拟 API 时如何保证请求正确发生?

模拟 API 时如何保证请求正确发生?

Go
吃鸡游戏 2022-10-17 10:13:38
假设我正在测试一个调用 Web 服务的功能,并且该服务被模拟为httptest.NewServerfunc TestSomeFeature(t *testing.T) {    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        w.WriteHeader(200)    }))    SomeFeature(server.URL, "foo")}func SomeFeature(host, a string) {    if a == "foo" {        http.Get(fmt.Sprintf("%v/foo", host))    }    if a == "bar" {        http.Get(fmt.Sprintf("%v/bar", host))    }}如何断言服务器是使用正确的 url 调用的,/foo如果使用错误的 url 调用或根本没有调用它,则测试失败?
查看完整描述

1 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

你可以这样做:


func TestSomeFeature(t *testing.T) {

    called := false

    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        // assert that strings.Contains(r.RequestURI, "/foo") is true

        called = true

        w.WriteHeader(200)

    }))


    SomeFeature(server.URL, "foo")

    // assert that called is true

}


查看完整回答
反对 回复 2022-10-17
  • 1 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信