golang ã®åä½ãã¹ããåå¼·ãã¦ãã¦ãå¤é¨ãªã½ã¼ã¹ã¸ã®ã¢ã¯ã»ã¹ãã¢ãã¯åããæ¹æ³ã調ã¹ã¦ããã gomock ã¨ããã®ããããã¨ãç¥ãã試ãããµã³ãã«ã§ãã
Â
ç°å¢æºå
Â
âââ go.mod
âââ model
â Â âââ book.go
âââ repository
â Â âââ book_repository.go
âââ service
  âââ book_service.go
Â
ãµã³ãã«ã¯ä»¥ä¸ã®ãããªæ§æã«ãããã¨æãã¾ãã
- book_service.go -> book é¢é£ã®ãã¸ãã¹ãã¸ãã¯ãæä¾ã
- book_repository.go -> book é¢é£ã® DB ã¢ã¯ã»ã¹å¨ãã®å¦çãæä¾ã
- book.go -> book æ§é ä½å®ç¾©
Â
åä½ãã¹ã対象ã®ã³ã¼ã
ç¶ãã¦ãã¹ã対象ã³ã¼ããç¨æãã¦ããã¾ãã
Â
book.go
book_repository.go
Â
Repository ã«DB ã¢ã¯ã»ã¹å¦çãããã¨ä»®å®ãã¦ããããå¾ã»ã©ã¢ãã¯ãã¾ãã
book_service.go
Â
ãã¡ãã® Service ãããRepository ã®å¦çãå¼ã³åºãã¾ãã
Â
åä½ãã¹ãã³ã¼ã
mock ã®çæ
ã¾ã㯠repository ã® mock ãä½æãã¾ãã
gomock ã§ã¯ããªã³ã¯å ã® README ã«æ¸ããã¦ããããã«ãmockgen ã³ãã³ã㧠mock ãèªåçæã§ããããã§ãã
Â
ããã§ã¯ãå ã«ä½æãã Repository ã® mock ãä½æãã¦ã¿ã¾ãã
repository ãã©ã«ãã«ç§»åãã¦ãä¸è¨ã®ã³ãã³ããå®è¡ãã¾ãã
Â
mockgen -source book_repository.go -destination mock/book_repository.go
Â
ããã¨ãmock ãã©ã«ããçæããããã®ä¸ã« book_repository.go ãçæããã¾ãã
Â
çæããã book_repository.go ã®ä¸è¨ã®import å¥ã§ã³ã³ãã¤ã«ã¨ã©ã¼ã«ãªã£ã¦ããã®ã§ã
Â
unittest ãã©ã«ãç´ä¸ã§ä¸è¨ã³ãã³ããå®è¡ã㦠gomock ã®ä¾åã追å ãã¾ãã
go mod tidy
Â
åä½ãã¹ãã³ã¼ã
repository ã® mock ãä½ããã®ã§ãç¶ãã¦åä½ãã¹ãã³ã¼ããæ¸ãã¾ãã
repository ã使ç¨ãã Service ã®åä½ãã¹ããæ¸ãã¦ããã¾ãã
Â
Â
ãã¹ãã®æ¤è¨¼ãç°¡æ½ã«ãããããgithub.com/stretchr/testify/assert ã使ç¨ãã¦ãã¾ãã
ã³ã³ãã¤ã«ã¨ã©ã¼ã«ãªãã¨æãã®ã§ã
go mod tidy
㧠assert ã®ä¾åé¢ä¿ã追å ãã¾ãã
Â
ãã¹ãã³ã¼ãã®å¤§ã¾ããªå®è£ ã®åè㯠gomockãªãã¡ã¬ã³ã¹ ããã
å ã«çæãã mock ããmock_db ã¨ãã¦ã¤ã³ãã¼ããã¦ãã¾ãã
mockObj.EXPECT().{ãã¹ã対象é¢æ°}.RETURN({æ»ãå¤})
ä¸è¨ã®å½¢å¼ã§æ»ãå¤ãæå®ã§ãã¾ãã
Â
ãã®å¾ãä¸è¨ã§è¨å®ãã mock ããService ã®ãã©ã¡ã¼ã¿ã¼ã¨ãã¦ä¸è¨ã®ããã«æ¸¡ããService ã®ã¡ã½ãããå¼ã³åºãã¦ãã¹ããå®è¡ãã¾ãã
Â
go test
PASS
ok    unittest/service     0.004s
Â
ãã¹ããPASSãã¾ããã
Â
ã¡ããã¨è¨å®ããå 容ã mock ã«åæ ããã¦ããã確èªãããããããã¨å¤±æã®ãã¹ãã±ã¼ã¹ã«ãã¦ã¿ã¾ãã
Â
Â
go test
--- FAIL: TestGetBookById (0.00s)
  book_service.go:13: Unexpected call to *mock_repository.MockBookRepository.GetBookById([200]) at /root/repos/go-samples/unittest/service/book_service.go:13 because:Â
    expected call at /root/repos/go-samples/unittest/service/book_service_test.go:19 doesn't match the argument at index 0.
    Got: 200 (int)
    Want: is equal to 100 (int)
  controller.go:269: missing call(s) to *mock_repository.MockBookRepository.GetBookById(is equal to 100 (int)) /root/repos/go-samples/unittest/service/book_service_test.go:19
  controller.go:269: aborting test due to missing call(s)
FAIL
exit status 1
FAIL   unittest/service     0.005s
Â
ãã¹ãã失æãããã¨ã確èªã§ãã¾ããã
Â
以ä¸ãµã³ãã«ã«ãªãã¾ãã
Â