Test22
V2EX  ›  问与答

Golang 的 fmt.printf()在单元测试中的一次异常

  •  
  •   Test22 · Aug 28, 2023 · 1477 views
    This topic created in 988 days ago, the information mentioned may be changed or developed.

    本人 golang 版本是 1.19.2 ,在公司中用的是 1.20 。 我知道是因为 format 时少了一个参数,我好奇的是为什么在执行 test 时编译不通过,而执行 main 的时候是可运行的。 不说废话,上代码,各位大哥看看是什么原因。

    main.go

    package main
    
    import (
    	"fmt"
    )
    
    func main() {
    	printLine()
    }
    
    func printLine() {
    	fmt.Printf("without arguments line", "arg
    ument")
    }
    //输出 without arguments line%!(EXTRA string=argument)
    

    main_test.go

    package main
    
    import "teig"
    
    func Test_printLine(t *testing.T) {
    	printLine()
    }
    //报错.\main.go:12:12: fmt.Printf call has arguments but no formatting directives
    
    2 replies    2023-09-06 17:54:36 +08:00
    standchan
        1
    standchan  
       Aug 29, 2023
    我试了一下,可能是 1.20 版本单元测试要求 fmt.Printf 需要加上格式占位符%s ,%d 之类的才能编译通过,你都用了 Printf 了。那就把%s,%d 之类的加上吧
    Test22
        2
    Test22  
    OP
       Sep 6, 2023
    @standchan 主要是我写了单元测试,但是项目中有不存在占位符的代码,而且还蛮多了,我也不好一行一行注释过去,所以才来问问😭
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5416 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 09:20 · PVG 17:20 · LAX 02:20 · JFK 05:20
    ♥ Do have faith in what you're doing.