Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the name of the currently executing testing test?

Tags:

go

In Go, how would I get the name of the currently executing test, the function name starting with Test, of the current test without passing it in manually?

like image 365
Matt Joiner Avatar asked Feb 21 '16 11:02

Matt Joiner


People also ask

How do I get the method name in JUnit?

As shown above, we can use the getMethodName method of class TestName to display the name of the test.

What is @after in JUnit?

org.junit If you allocate external resources in a Before method you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception.

What is the sequence of test execution?

In JUnit, the execution sequence of the same project is: InitTestCase (setUp) TestCase1 (testMethod1) EndTestCase (tearDown)


2 Answers

Just use the Name() method:

func TestSomethingReallyCool(t *testing.T) {
    t.Logf("Test name is %s", t.Name())
}

Here's the docs and here's the code.

like image 88
Francesco Casula Avatar answered Nov 07 '22 18:11

Francesco Casula


This is an interesting question. When you define a test, you pass around a struct that represents the test itself:

func TestSomething(t *testing.T) {

testing.T is defined as follows:

type T struct {
    common
    name          string    // Name of test.
    startParallel chan bool // Parallel tests will wait on this.
}

So the struct t has the name of the test in a field called name. However, for some reason, the name is not exported and there is no public accessor that will return it. Therefore, you can't access it directly.

There is a workaround. You can use the reflect package to access the unexported name and get the test name from t:

v := reflect.ValueOf(*t)
name := v.FieldByName("name")

// name == "TestSomething"

I'm not sure if this is the best approach, but I was not able to find another reasonable solution to access name from the testing package.

like image 44
Simone Carletti Avatar answered Nov 07 '22 17:11

Simone Carletti