英文:
hex-arc golang - overcome import cycling error when testing
问题
我在测试我的Go项目中的foo_handler时遇到了问题。我的项目结构如下:
├── 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从server.go调用NewApi(),server.go使用router.go中的NewRouter()创建和实例化一个Router结构体,router.go又创建和实例化FooHandler结构体。换句话说:
main.go -> server.go -> router.go -> foo_handler.go
我需要使用api来建立和获取一个新的router对象来测试foo_handler,但是我遇到了一个错误:
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
我如何在不更改测试目录的情况下解决这个错误?我漏掉了什么?如果我将foo_handler_test.go移动到一个bar目录中,测试就可以正常运行。
英文:
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
得分: 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".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论