3

Assume for a moment I have a Go package with numerous interfaces. For this example, I'd focus on one called Middleware defined in middleware.go:

type Middleware interface {
  // some functions
}  

I have some other parts of the system that uses it, so to better help test those parts of the system, I created a mock implementation by hand in mock_middleware.go:

type MockMiddleware struct {

}  

// implementations

When building the binary without tests, how do I exclude the mock classes from being built into the binary? I'm aware that middleware_test.go will be excluded, but I'd don't want to name all my mocks with that convention so as not to confuse actual tests with implementations to support testing.

bloudraak
  • 5,902
  • 5
  • 37
  • 52
  • 3
    AFAIK, Go's compiler eliminates dead code. So your mock types, if they are used only in tests, may already be excluded from the final binary. Also, possible duplicate https://stackoverflow.com/a/42827979/965900 – mkopriva Jul 29 '18 at 20:14
  • That is a fair point. I'm wasting time compiling it, but for the size of my project isn't too much. I guess it will be an issue when your application becomes rather large (e.g. 100,000s of lines of code). – bloudraak Jul 30 '18 at 14:11

1 Answers1

2

One way could be to use Build Constraints.

Go even supports a built in ignore tag, but I'm not really sure of its interaction with the testing/benchmark toolchain:

To keep a file from being considered for the build:

// +build ignore

dm03514
  • 54,664
  • 18
  • 108
  • 145
  • I looked at build constraints, but couldn't find documentation or examples that actually worked within this scenario. Any suggestions on what to explore? – bloudraak Jul 30 '18 at 14:13
  • Sorry my only experience with them is for partitioning up a test suite and only executing tests with certain tags, ie unit, integration, service. Soundcloud illustrates how to do this here: http://peter.bourgon.org/go-in-production/#testing-and-validation – dm03514 Jul 30 '18 at 14:31