dsjhejw3232 2015-03-06 23:30
浏览 132
已采纳

如何在Go测试输出中确定行号?

Let's consider this simple testing code.

(Note: assertSomething is super simple here, but normally I'd write a more specialised helper for the task at hand that would look at multiple things and could report more than one type of error.)

package hello

import "testing"

func TestFoo(t *testing.T) {
    assertSomething(t, 2+2 == 4) // line 6
    assertSomething(t, 2+3 == 6) // line 7
}

func assertSomething(t *testing.T, expected bool) {
    if !expected {
        t.Error("Something's not right") // line 12
    }
}

When I run go test, I get the following:

--- FAIL: TestFoo (0.00s)
    hello.go:12: Something's not right
FAIL
exit status 1
FAIL    kos/hello   0.008s

I have two questions:

1) The error points to line 12 - why? How does t.Error find out which line it was called from?

2) In the helper, I'd like to specify that t.Error should look stack level higher to determine the line number to print, so that I would get a message like this:

--- FAIL: TestFoo (0.00s)
    hello.go:7: Something's not right

Python allows me to do this, for instance, in warnings.warn("message", stacklevel=2) - how would I implement the equivalent here?

  • 写回答

2条回答 默认 最新

  • drxrgundk062317205 2018-03-23 07:56
    关注

    Things have changed since go 1.9.

    Helper() method has been added to testing.T and testing.B. It's intended to be invoked from testing helpers such as assertSomething to indicate the function is a helper and we're not interested in line numbers coming from it.

    package main
    
    import "testing"
    
    func TestFoo(t *testing.T) {
        assertSomething(t, 2+2 == 4) // line 6
        assertSomething(t, 2+3 == 6) // line 7
    }
    
    func assertSomething(t *testing.T, expected bool) {
        if !expected {
            t.Helper()
            t.Error("Something's not right") // line 12
        }
    }
    

    The output contains correct line numbers:

    === RUN   TestFoo
    --- FAIL: TestFoo (0.00s)
        main.go:7: Something's not right
    FAIL
    

    You can also try it on Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。