Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

Go testing get caller line number

Example code:

package main

import "testing"

func TestOne(t *testing.T) {
    assertEq(t, "A", "B")
    assertEq(t, "B", "B")
    assertEq(t, "C", "X")
}

func TestTwo(t *testing.T) {
    assertEq(t, "A", "A")
    assertEq(t, "B", "B")
    assertEq(t, "C", "D")
}

func assertEq(t *testing.T, a, b string) {
    if a != b {
        t.Fatalf("%s != %s, in %s", a, b, t.Name())
    }
}

Output:

=== RUN   TestOne
    prog.go:19: A != B, in TestOne
--- FAIL: TestOne (0.00s)
=== RUN   TestTwo
    prog.go:19: C != D, in TestTwo
--- FAIL: TestTwo (0.00s)
FAIL

If I call assertEq() many times, it is difficult to find what is line where the test failed. Can I get the caller line number?

question from:https://stackoverflow.com/questions/65856284/go-testing-get-caller-line-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use runtime.Caller.

package main

import (
    "testing"
    "runtime"
)

func TestOne(t *testing.T) {
    assertEq(t, "A", "B")
    assertEq(t, "B", "B")
    assertEq(t, "C", "X")
}

func TestTwo(t *testing.T) {
    assertEq(t, "A", "A")
    assertEq(t, "B", "B")
    assertEq(t, "C", "D")
}

func assertEq(t *testing.T, a, b string) {
    if a != b {
        _, f, l, _ := runtime.Caller(1)
        t.Fatalf("%s:%d %s != %s, in %s", f, l, a, b, t.Name())
    }
}

https://play.golang.org/p/EWoYhiGugDg


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...