


In this article, php editor Xiaoxin will introduce you to a common error that occurs when writing unit tests in the Go language, that is, assertion errors. When we write unit tests, we sometimes encounter situations where the return value cannot be determined, which can lead to unexpected method call errors. In this article, we will discuss the causes and solutions to this problem to help you better handle assertion errors and ensure the accuracy and reliability of your unit tests.
Question content
I use testify
in go to write unit tests for my service methods. All methods work fine except the update method, because during the update In the method, I call another method of the same service ("getbyid") in the update method.
Implement the update method in my service:
func (ts *teamservice) update(team *team.team) apperror { t, err := ts.teamrepo.getbyid(team.id) if err != nil { return err } if t.teamownerid != team.teamownerid { return newforbiddenerror(forbiddenerr) } return ts.teamrepo.update(team) }
mockrepo update method:
func (t *teamrepomock) update(team *team.team) apperror { args := t.called(team) if args.error(0) != nil { return newnotfounderror(args.error(0)) } return nil }
Test implementation:
func testupdate(t *testing.t) { _, teamidgen, playeridgen := setupconfig() t.run("update a team", func(t *testing.t) { teamrepo, _, ts := setupteamservice(teamidgen, playeridgen) teamrepo.on("update", testteam1).return(nil) result := ts.update(testteam1) assert.nil(t, result) }) t.run("update a team fails", func(t *testing.t) { teamrepo, _, ts := setupteamservice(teamidgen, playeridgen) expected := oopserr teamrepo.on("update", testteam1).return(expected) result := ts.update(testteam1) assert.equalvalues(t, expected.error(), result.error()) }) }
Now when I run the test I get the following error:
--- FAIL: TestUpdate (0.01s) --- FAIL: TestUpdate/Update_a_team (0.01s) panic: assert: mock: I don't know what to return because the method call was unexpected. Either do Mock.On("GetByID").Return(...) first, or remove the GetByID() call. This method was unexpected: GetByID(string) 0: "" at: [/home/waleem/Desktop/project/eazykhel_server/services/teamservice/team_service_init_test.go:18 /home/waleem/Desktop/project/eazykhel_server/services/teamservice/team_service.go:146 /home/waleem/Desktop/project/eazykhel_server/services/teamservice/team_service_test.go:277] [recovered] panic:
I tried calling .on("update")
before and after calling mock.on("getbyid")
in the test function implementation but it doesn't work and I also modified the mockrepo update function but it didn't work.
Solution
Let me try to help you solve your problem. I copied the repository with some simplifications just to post the relevant code. If I'm not wrong in your solution, there is a service (teamservice
) that calls some methods provided by the underlying package (teamrepo
). You want to test the update
method of the teamservice
structure. After reviewing, let me show the code first and then I will try to explain each file:
repo/repo.go
package repo type team struct { id int teamownerid int name string } type teamrepo struct{} func (t *teamrepo) getbyid(id int) (team, error) { return team{id: id, teamownerid: id, name: "myteam"}, nil } func (t *teamrepo) update(team team) error { return nil }
In this file we can find the method to simulate. The methods are: getbyid
and update
. Obviously this isn't your actual code, but that doesn't matter right now.
services/service.go
package services import ( "errors" "testifymock/repo" ) type teamservice struct { tr teamrepointerface } func newteamservice(repo teamrepointerface) *teamservice { return &teamservice{ tr: repo, } } type teamrepointerface interface { getbyid(id int) (repo.team, error) update(team repo.team) error } func (ts *teamservice) update(team *repo.team) error { t, err := ts.tr.getbyid(team.id) if err != nil { return err } if t.teamownerid != team.teamownerid { return errors.new("forbidden") } return ts.tr.update(*team) }
Here we can see in the test code the service that will become our system under test (sut
). With dependency injection, we will take advantage of the functionality provided by the repo
package injected through the interface teamrepointerface
.
services/service_test.go
package services import ( "errors" "testing" "testifymock/repo" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) // 1. declare the mock struct type teamRepoMock struct { mock.Mock } // 2. implement the interface func (m *teamRepoMock) GetByID(id int) (repo.Team, error) { args := m.Called(id) return args.Get(0).(repo.Team), args.Error(1) } func (m *teamRepoMock) Update(team repo.Team) error { args := m.Called(team) return args.Error(0) } func TestUpdate(t *testing.T) { t.Run("GoodUpdate", func(t *testing.T) { // 3. instantiate/setup mock repoMock := new(teamRepoMock) repoMock.On("GetByID", 1).Return(repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}, nil).Times(1) repoMock.On("Update", repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}).Return(nil).Times(1) sut := NewTeamService(repoMock) err := sut.Update(&repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}) // 4. check that all expectations were met on the mock assert.Nil(t, err) assert.True(t, repoMock.AssertExpectations(t)) }) t.Run("BadUpdate", func(t *testing.T) { // 3. instantiate/setup mock repoMock := new(teamRepoMock) repoMock.On("GetByID", 1).Return(repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}, nil).Times(1) repoMock.On("Update", repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}).Return(errors.New("some error while updating")).Times(1) sut := NewTeamService(repoMock) err := sut.Update(&repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}) // 4. check that all expectations were met on the mock assert.Equal(t, "some error while updating", err.Error()) assert.True(t, repoMock.AssertExpectations(t)) }) }
In the code you can find some comments to better detail what is happening. As you can guess, the problem is that this call is missing in the code:
repomock.on("getbyid", 1).return(repo.team{id: 1, teamownerid: 1, name: "test"}, nil).times(1)
If you run my solution it should work for you too.
If this solves your problem or you have any other questions, please let me know!
The above is the detailed content of Assertion: Mock: I don't know what to return because the method call was unexpected Error while writing unit test in Go. For more information, please follow other related articles on the PHP Chinese website!

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

go语言需要编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言,也就说Go语言程序在运行之前需要通过编译器生成二进制机器码(二进制的可执行文件),随后二进制文件才能在目标机器上运行。

go语言能编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言。对Go语言程序进行编译的命令有两种:1、“go build”命令,可以将Go语言程序代码编译成二进制的可执行文件,但该二进制文件需要手动运行;2、“go run”命令,会在编译后直接运行Go语言程序,编译过程中会产生一个临时文件,但不会生成可执行文件。

删除map元素的两种方法:1、使用delete()函数从map中删除指定键值对,语法“delete(map, 键名)”;2、重新创建一个新的map对象,可以清空map中的所有元素,语法“var mapname map[keytype]valuetype”。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool