JUnit getMethodName returns null



我正在运行一些Selenium测试,但我无法访问我的测试方法的名称。 我想在日志中打印一些东西,例如"开始测试:foobarbaz">

我所有的测试类都继承了一个公共的"AbstractTest"类,其中包含:

@Rule TestName name = new TestName();
@BeforeTest
public void testSetUp(){
System.out.println(name);
System.out.println(name.getMethodName());
}

但输出是:

org.junit.rules.TestName@59f63e24
null

为什么 getMethodName(( 方法返回 null?

我的绒球摘录.xml可能有用...

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>

正如评论中所指出的,这个问题混合了JUnit 4,JUnit Jupiter(JUnit 5(和TestNG,你可能只想关注一个。

在JUnit Jupiter中,这些信息可以通过ExtensionContext访问。我不知道一个内置的扩展可以打印它,但是自己编写一个

扩展很容易:
public class NamePrinter implements BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext extensionContext) throws Exception {
extensionContext.getTestMethod().ifPresent(m -> System.out.println(
"Running method: " + m.getName() + 
" [display name: " + extensionContext.getDisplayName() + ")"));
}
}

然后你可以把它作为一个扩展:

@ExtendWith(NamePrinter.class)
public class MyClassTest {
@Test
public void someTest() {
System.out.println("This is a test");
}
}

TestNG 解决方案有效(在另一个线程中找到它(: https://stackoverflow.com/a/12202455/7093031

import java.lang.reflect.Method;
public class Test {
@BeforeMethod
public void handleTestMethodName(Method method){
String testName = method.getName(); 
}
}

最新更新