views:

72

answers:

3

Basically I have a tear down method that I want to log to the console which test was just run. How would I go about getting that string?

I can get the class name, but I want the actual method that was just executed.

Class testSomething() {
    @AfterMethod
    public void tearDown() {
        system.out.println('The test that just ran was....' + getTestThatJustRanMethodName()');
    }
    @Test
    public void testCase() {
       assertTrue(1==1);
    }
}

should output to the screen: "The test that just ran was.... testCase"

However I don't know the magic that getTestThatJustRanMethodName should actually be.

+2  A: 

An easy (but kinda dirty) way would be just to have a local field and update it in every test method run

Class testSomething() {
    private String lastCall;

    @AfterMethod
    public void tearDown() {
        System.out.println("The test that just ran was: " + lastCall);
    }

    @Test
    public void testCase() {
        lastCall = "testCase()";
        assertTrue(1 == 1);
    }
}
victor hugo
+ 1 for having my brain in your head with faster reflexes
Zak
Haha yeah it was a race against time, I just typed as fast as possible
victor hugo
I've got over 600 test methods. this is not an acceptable solution :/.
Zachary Spencer
+1  A: 

This is made available as below in junit4.7 onwards.

http://github.com/KentBeck/junit/raw/23ffc6baf5768057e366e183e53f4dfa86fbb005/doc/ReleaseNotes4.7.txt

  • The TestName Rule makes the current test name available inside test methods:

    public class NameRuleTest {
        @Rule public TestName name = new TestName();
    
    
    
    @Test public void testA() {
        assertEquals("testA", name.getMethodName());
    }
    
    
    @Test public void testB() {
        assertEquals("testB", name.getMethodName());
    }
    
    }

Not sure if it works directly in setup/tear down but you could store it a class level var as it executes each test case.

daedlus
The junit tag was misleading. I have remove it.
OscarRyz
Doh. Good point.
Zachary Spencer
+7  A: 

Declare a parameter of type ITestResult in your @AfterMethod and TestNG will inject it:

@AfterMethod
public void am(ITestResult result) {
  System.out.println("method name:" + result.getMethod().getMethodName();
}
Cedric Beust
Awesome Cedric! That's fantastic!
Zachary Spencer