dongwei4444 2019-04-23 18:45
浏览 43

在Go单元测试中使用两个不同的模拟

I am learning to do unit testing using mocks in Go for the first time, using gomock's mockgen utility. My unit tests work fine except for one of them. The method-under-test has two dependencies: one on a database, and the other on an external service it makes rest api calls to. The mock for the database (mockRepo) works fine in that the method-under-test properly invokes the mock instead of the actual repo code. The mock for the rest client, however, continues to invoke the actual rest client and not the mock code. I can't figure out why. Can someone explain why and help fix?

Here is my unit test:

func TestService_CreateWorkspace(t *testing.T) {
    ts := NewTestService(t)
    defer ts.mockCtrl.Finish()

    ts.mockClient.EXPECT().POST(gomock.Any(), gomock.Any(), gomock.Any()).Times(1).Return(&http.Response{StatusCode: 200}, nil)

    testWs := TestWorkspaces()["max-ws"]
    ts.mockRepo.EXPECT().Create(testWs).Times(1).Return(&testWs, nil)

    ws, err := ts.service.CreateWorkspace(&testWs)

    assert.Equal(t, testWs, ws)
    assert.NoError(t, err)
}

Here is the code for NewTestService:

type TestService struct {
    mockCtrl   *gomock.Controller
    mockClient *MockRestClient
    mockRepo   *MockRepository
    service    Service
}

func NewTestService(t *testing.T) *TestService {
    mockCtrl := gomock.NewController(t)
    mockRepo := NewMockRepository(mockCtrl)
    mockClient := NewMockRestClient(mockCtrl)
    return &TestService{
        mockCtrl:   mockCtrl,
        mockClient: mockClient,
        mockRepo:   mockRepo,
        service:    NewService(mockRepo),
    }
}

Is there an issue with assigning the same mock controller to two different mock objects? Not really sure what's going on here. Any help appreciated.

  • 写回答

1条回答 默认 最新

  • dongshao6591 2019-04-24 11:56
    关注

    I resolved this as Adrian in the comments above suggested. I was missing a way to pass the mock client into the NewService and ended up adding a client parameter to NewService.

    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码