[英]JUnit getMethodName returns null
I'm running some Selenium tests and I'm not able to access my test methods' names.我正在运行一些 Selenium 测试,但无法访问我的测试方法的名称。 I would like to print something in the logs like "Starting test: foobarbaz"我想在日志中打印一些东西,比如“开始测试:foobarbaz”
All my test classes inherit a public "AbstractTest" class, which contains:我所有的测试类都继承了一个公共的“AbstractTest”类,其中包含:
@Rule TestName name = new TestName();
@BeforeTest
public void testSetUp(){
System.out.println(name);
System.out.println(name.getMethodName());
}
But the output is:但输出是:
org.junit.rules.TestName@59f63e24
null
Why is getMethodName() method returning null?为什么 getMethodName() 方法返回 null?
An extract of my pom.xml that may be useful...我的 pom.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>
As noted in the comments, the question mixes JUnit 4, JUnit Jupiter (JUnit 5) and TestNG, and you probably want to focus on just one.如评论中所述,该问题混合了 JUnit 4、JUnit Jupiter (JUnit 5) 和 TestNG,您可能只想关注其中一个。
In JUnit Jupiter, this information is accessible via the ExtensionContext
.在 JUnit Jupiter 中,可以通过ExtensionContext
访问此信息。 I'm not aware of a built-in extension that just prints it, but it's quite easy to write one yourself:我不知道只打印它的内置扩展,但自己编写一个很容易:
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() + ")"));
}
}
And then you can just use it as an extension:然后你可以将它用作扩展:
@ExtendWith(NamePrinter.class)
public class MyClassTest {
@Test
public void someTest() {
System.out.println("This is a test");
}
}
The TestNG solution worked (found it in another thread): https://stackoverflow.com/a/12202455/7093031 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.