-1

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.

Dana
  • 57
  • 1
  • 4
  • Why do you have to create a router to test FooHandler? Why not call it directly? – Peter Jun 18 '23 at 09:40
  • @Peter Can you elaborate? I have to create a router because i'm registering all the routes and in the foo_handler_test i'm trying to test against these routes with mock requests and responses – Dana Jun 18 '23 at 09:48
  • You simply call FooHandler.ServeHTTP in the test instead of the router's ServeHTTP. – Peter Jun 18 '23 at 14:11

1 Answers1

2

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".

Peter
  • 29,454
  • 5
  • 48
  • 60
Volker
  • 40,468
  • 7
  • 81
  • 87
  • My current intuition is to create dir for tests with subdirs of unit tests / integration_tests, but all guides i've read so far recommend to put test files within the same directory of the source file – Dana Jun 18 '23 at 09:53
  • @Dana Tests in Go typically belong the the package. This has nothing to do with "directories". – Volker Jun 18 '23 at 10:28