简体   繁体   English

如何从 go 项目根文件夹运行测试?

[英]How to run tests from go project root folder?

I am working through the text, "Writing an Interpreter in Go" by Thorsten Ball in order to learn about the language.我正在阅读 Thorsten Ball 的“Writing an Interpreter in Go”一文,以了解该语言。

Project Directory looks like this:项目目录如下所示:

Interpreter/
|---code/
|   |---token/
|   |   |---token.go
|   |   |---go.mod
|   |---lexer/
|       |---lexer_test.go
|       |---go.mod
|---go.mod

I created the go.mod files in this manner我以这种方式创建了go.mod文件

>go mod init monkey
>cd token
>go mod init token
>cd ../lexer
>go mod init lexer

I added this line to the go.mod file in the lexer module我将此行添加到 lexer 模块中的go.mod文件中

replace monkey/token => ../token

On running go test from inside the lexer folder, I get the expected output as mentioned in the book, but I realize this is not an indicator of the project being setup properly.在从 lexer 文件夹中运行go test时,我得到了本书中提到的预期 output,但我意识到这并不是项目设置正确的指标。

>go test
# lexer [lexer.test]
./lexer_test.go:26:7: undefined: New
FAIL    lexer [build failed]

But on running the tests as mentioned in the book, ie from the root folder code in the following manner:但是在运行本书中提到的测试时,即以以下方式从根文件夹代码中运行:

go test ./lexer

go is unable to resolve the lexer package and I get the following error go 无法解析词法分析器 package,我收到以下错误

main module (monkey) does not contain package monkey/lexer

Is there something that needed to be added to the go.mod file in the root folder that fixes this?是否需要将某些内容添加到根文件夹中的go.mod文件中以解决此问题?

As @mkopriva notes, the simple solution is to delete the go.mod files from the token and lexer directories.正如@mkopriva 所说,简单的解决方案是从tokenlexer目录中删除go.mod文件。

In general, a Go project should have a single go.mod file at the project root: each go.mod file indicates a self-contained module.一般来说,一个 Go 项目应该在项目根目录下有一个go.mod文件:每个go.mod文件表示一个独立的模块。

The solution was解决方案是

$ cd 01/src/monkey
$ go mod init monkey
$ go test ./lexer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM