Which directory to put mocks?
Asked Answered
T

2

8

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.

Thylacine answered 19/2, 2017 at 21:46 Comment(0)
B
6

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.

Betroth answered 17/7, 2018 at 16:35 Comment(0)
F
1

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 
Followthrough answered 28/5, 2023 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.