Go-Mock http.Response主体与一个文件

Go-Mock http.Response主体与一个文件,go,testing,mocking,Go,Testing,Mocking,我正在测试一个执行对外部服务调用的Go函数。下面是函数: func (gs *EuGameService) retrieveGames(client model.HTTPClient) (model.EuGamesResponse, error) { req, err := http.NewRequest(http.MethodGet, gs.getGamesEndpoint, nil) if err != nil { log.Fatal("Error while cre

我正在测试一个执行对外部服务调用的Go函数。下面是函数:

func (gs *EuGameService) retrieveGames(client model.HTTPClient) (model.EuGamesResponse, error) {
   req, err := http.NewRequest(http.MethodGet, gs.getGamesEndpoint, nil)
   if err != nil {
      log.Fatal("Error while creating request ", err)
      return nil, err
   }

   resp, err := client.Do(req)
   if err != nil {
       log.Fatal("Error while retrieving EU games", err)
       return nil, err
   }

   var euGames model.EuGamesResponse
   decoder := json.NewDecoder(resp.Body)
   decoder.Decode(&euGames)

   return euGames, nil
}
为了正确地测试它,我尝试注入一个模拟客户端

type HTTPClient interface {
    Do(req *http.Request) (*http.Response, error)
}

type mockClient struct{}

func (mc *mockClient) Do(req *http.Request) (*http.Response, error) {
    mock, _ := os.Open("../stubs/eugames.json")
    defer mock.Close()

    r := ioutil.NopCloser(bufio.NewReader(mock))

    return &http.Response{
        Status:     string(http.StatusOK),
        StatusCode: http.StatusOK,
        Body:       r,
    }, nil
}

文件
eugames.json
包含几个游戏。但由于某些原因,身体总是空的!我错过了什么?我试着用一个常数来表示文件内容,它可以工作,游戏被正确解码。因此,我假设我对文件的使用有问题。

如果您延迟关闭文件,尝试读取响应正文的代码将无法从关闭的文件中读取。@mkopriva您是对的。我是Go的初学者:我应该把内容复制到一个字节片中,然后从该片中创建一个阅读器吗?。。。您应该可以这样来修复它:(closefile方法实际上不是必需的,但是,如果我没记错的话,您将无法在初始化文件之前,即在调用初始化文件的
retrieveGames
之前,推迟mc.f.Close())将文件读入缓冲区,并将其用作正文,即使不是更好,也一样好。请注意:您可以使用net/http.ReadResponse从磁盘读取整个响应。这对测试非常方便。如果您延迟关闭文件,则试图读取响应正文的代码将无法从关闭的文件中读取。@mkopriva您说得对。我是Go的初学者:我应该把内容复制到一个字节片中,然后从该片中创建一个阅读器吗?。。。您应该可以这样来修复它:(closefile方法实际上不是必需的,但是,如果我没记错的话,您将无法在初始化文件之前,即在调用初始化文件的
retrieveGames
之前,推迟mc.f.Close())将文件读入缓冲区,并将其用作正文,即使不是更好,也一样好。请注意:您可以使用net/http.ReadResponse从磁盘读取整个响应。这是非常方便的测试。