将模拟数据放在哪个目录?

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

Which directory to put mocks?

问题

我最近一直在尝试使用Go语言官方支持的测试模拟框架GoMock。我想知道将这些模拟文件放在哪个位置最合理。

我的当前目录结构如下。这是Go项目应该的结构吗?

appname
|-- gateways
    |-- gateway1.go
    |-- gateway1_test.go
    |-- gateway2.go
    |-- gateway2_test.go
    |-- mocks
        |-- gateway1.go
        |-- gateway2.go

这个结构受到了Ben Johnson在这里的演讲的影响。

英文:

I've been most recently experimenting with GoMock, the test mocking framework supported by the official creators of the Go language. I was wondering where is the most reasonable place to put these mocked files.

My current directory structure is as follows. Is this how Go projects should be structured?

appname
|-- gateways
    |-- gateway1.go
    |-- gateway1_test.go
    |-- gateway2.go
    |-- gateway2_test.go
    |-- mocks
        |-- gateway1.go
        |-- gateway2.go

This is slightly influenced by Ben Johnson's talk here.

答案1

得分: 4

我倾向于遵循本文,作者是Ben Johnson。

文章链接

总的来说,将共享的模拟对象放在一个包中的做法是不错的。这里值得指出的一点是,如果你不将模型定义在gateways包之外,可能会出现导入循环的问题。

  1. gateways定义了模型
  2. mocks导入了gateways.Model
  3. gateways为了测试而导入了mocks

有两种方法可以解决这个问题;第一种方法是将模型移到domain中,即gateways之外的根包(请参考文章中的示例)。或者只通过在测试文件中使用gateways_test作为包来测试gateways包的公共接口。

英文:

I tend to follow this article also by Ben Johnson

Link to article

In general this approach of having a package for your shared mocks is a good one. One thing worth pointing out here is that if you don't define your models outside of the gateways package you could get an import cycle.

  1. gateways defines models
  2. mocks imports gateways.Model
  3. gateways imports mocks for tests

There are 2 ways to fix this; the first is just to move your models into domain, a root package outside gateways (see article for examples). Or only test the public interface of your gateways package by using gateways_test as the package in your test files.

答案2

得分: 0

我将其放在与我的接口相同的包中,我认为这是一个好的位置,因为它与继承的结构分开。我认为你的项目结构不好,我更喜欢以下方式(基于DDD架构):

示例:

appname
|-- gateways
    |-- gateway.go // 这个文件包含接口和模拟对象
    |-- gateway1
        |-- gateway1.go
        |-- gateway1_test.go 
    |-- gateway2
        |-- gateway2.go
        |-- gateway2_test.go 
英文:

I place it in the same package as my interface and in my opinion it's a good place because it's separated from inherited structs I think your project structure is not good I rather do below (its base on DDD architecture)

example

appname
|-- gateways
    |-- gateway.go //this file contain interface and mocks 
    |-- gateway1
        |-- gateway1.go
        |-- gateway1_test.go 
    |-- gateway2
        |-- gateway2.go
        |-- gateway2_test.go 

huangapple
  • 本文由 发表于 2017年2月20日 05:46:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/42333303.html
匿名

发表评论

匿名网友

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

确定