你在哪里存储可重用的模拟数据?

huangapple go评论145阅读模式
英文:

Where do you store reusable mocks?

问题

你能解释一下正确的单元测试组织方式吗?例如,如果我想要模拟我的结构体依赖,我需要创建一个模拟依赖,它“实现”了某个接口。

我应该在哪里创建这个模拟依赖?它应该在同一个测试文件中创建吗?但是如果我在另一个测试中也需要它怎么办?Go语言不允许在同一个包的两个不同文件中定义同名的结构体(例如UserServiceMock)。那么,最好在哪里定义这个模拟结构体呢?

还有一个问题。我应该自己实现这种模拟,还是有一些库/工具可以帮助我实现它?

英文:

Could you please explain what is a correct way of organizing unit tests? For instance if would like to mock my struct dependencies I need to create a mock dependency which "implements" some interface.

Where should I create this mock? Should it be created in the same test file? But then what if I will need it in another test? Go doesn't allow to define struct with a same name (e.g. UserServiceMock) in 2 different files of the same package. Then what is the best place to define this mock struct?

And another question. Should I implement this kind of mocks by myself or there are some libraries / tools which allow me to do it?

答案1

得分: 2

我将我的模拟对象存储在一个模拟包中,这样我就可以从不同的测试包中调用它们,并在我的测试中使用该包名作为我正在模拟依赖项的指示。例如:

mock.UserService

你可以创建一个生成器或使用GoMock

英文:

I store my mocks in a mock package so I can call them from different test packages and use that package name in my tests as an indication that I am mocking a dependency. For example:

mock.UserService

You could create a generator or use GoMock

答案2

得分: 1

我也遇到了这个问题,我通过在一个单独的文件中放置接口的模拟和声明来解决它。

使用mockery来生成它们,这将在相同的文件夹中创建模拟。根据上述命令,它将为service目录中存在的每个接口生成一个单独的文件。例如:mock_MyInterface.go

如果你不使用-inpkg标志,它将在默认文件夹mocks中创建模拟,但它不会为模拟实现添加任何前缀,这将在你在单元测试中导入模拟包时创建问题,因为由于模拟和原始实现具有相同的名称,会发生冲突。

英文:

I also faced this issue and I resolved it by putting mocks of interface along with their declaration in a separate file.

mockery -dir=service  -all -inpkg

I used mockery to generate them and this will create mock in the same folder. As per the above command, it will generate a separate file for each interface exist in service directory. For e.g.: mock_MyInterface.go.

if you don't use -inpkg flag, it will create mocks in a default folder mocks but it does not add any prefix in mocked implementation and thus it will create problem when you will import mocks package in unit test because you will get conflict due to mock and original implementation with the same name.

huangapple
  • 本文由 发表于 2017年3月12日 01:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/42738391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定