hex-arc golang - overcome import cycling error when testing

100 views Asked by At

I am having trouble testing foo_handler in my Go project. My project has the following structure:

├── Makefile
├── cmd
│   └── main.go
├── go.mod
├── go.sum
└── internal
    ├── api
    │   ├── router.go
    │   └── server.go
    ├── core
    │   ├── domain
    │   │   └── foo.go
    ├── handlers
    │   ├── foo_handler.go
    │   ├── foo_handler_test.go

main.go invokes NewApi() from server.go, which in turn creates and instantiates a Router struct using the NewRouter() in router.go, which in turn creates and instantiates the FooHandler struct. So, in other words:

main.go -> server.go -> router.go -> foo_handler.go

I need to use api to establish and get a new router object to test foo_handler, but I get an error:

FAIL tmp-svc/internal/handlers [setup failed]
# tmp-svc/internal/handlers
package tmp-svc/internal/handlers
    imports tmp-svc/internal/api: import cycle not allowed in test
FAIL

How can I overcome this error without changing the test directory? What am I missing? If I move foo_handler_test.go to a bar directory, the test runs without any issue.

1

There are 1 answers

3
Volker On

How can I overcome this error without changing the test directory?

You cannot (in a sensible way). You can try an interface dance.

What am I missing?

Hexagonal (or any other) architecture is not about folders but about software architecture. Somehow software architecture is considered "folder-layout" nowadays. You can put everything in one package and still have "hexagonal architecture".