1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Go】mockが期待した値を返さない

Last updated at Posted at 2024-03-11

問題

  • mockが期待した値を返してくれない

回答

  • mockオブジェクトを使いまわしてないですか?
    • mockに異なる振る舞いをさせたいときは、新たなmockオブジェクトを用意する必要があります
    • 逆に、新たに用意しないと、前回のonメソッドの指示が更新されず、残ってしまいます

	// Test 1; OK
	r := repository.NewMockRepository()
	r.On("FetchData", mock.Anything, 1).
		Return(&model.Data{}, nil)
	h := NewHandler(r, nil)

	_, err := h.HandleRequest()(writer, request)
	assert.Equal(t, nil, err)

	// Test 2; error occured in repository
	r := repository.NewMockRepository()  // ←----------- ここ!!! ---------
    testErr := errors.New("test error")
	r.On("FetchData", mock.Anything, 1).
		Return(&model.Data{}, testErr)
	h = NewHandler(r, nil)

	_, err := h.HandleRequest()(writer, request)
	assert.Equal(t, testErr, err)
  • 強調部が抜けていると、Test1で指示した振る舞いが残ってしまい、Test2でもFetchData関数はnilを返してしまいます

あとがき

  • これだけのことですが、各種生成AIも指摘してくれず、かなり詰まりました。つらい。
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?