java 在JUNIT中的@Before中获取当前正在执行的@Test方法的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17230413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:23:33  来源:igfitidea点击:

Get the name of currently executing @Test method in @Before in JUNIT

javajunit

提问by user2508111

I want to get the name of currently executing TestCase Method in @Before method. Example

我想在@Before 方法中获取当前正在执行的 TestCase 方法的名称。例子

public class SampleTest()
{
    @Before
    public void setUp()
    {
        //get name of method here
    }

    @Test
    public void exampleTest()
    {
        //Some code here.
    }
 }

回答by Jaydeep Patel

As discussed here, try using @Rule and TestName combination.

正如这里所讨论的,尝试使用 @Rule 和 TestName 组合。

As per the documentationbefore method should have test name.

根据方法之前的文档应该有测试名称。

Annotates fields that contain rules. Such a field must be public, not static, and a subtype of TestRule. The Statement passed to the TestRule will run any Before methods, then the Test method, and finally any After methods, throwing an exception if any of these fail

注释包含规则的字段。这样的字段必须是公共的,而不是静态的,并且是 TestRule 的子类型。传递给 TestRule 的 Statement 将运行任何 Before 方法,然后是 Test 方法,最后是任何 After 方法,如果这些方法中的任何一个失败,则抛出异常

Here is the test case using Junit 4.9

这是使用 Junit 4.9 的测试用例

public class JUnitTest {

    @Rule public TestName testName = new TestName();

    @Before
    public void before() {
        System.out.println(testName.getMethodName());
    }

    @Test
    public void test() {
        System.out.println("test ...");
    }
}

回答by darijan

Try using a @Ruleannotation with org.junit.rules.TestNameclass

尝试@Ruleorg.junit.rules.TestName类中使用注释

@Rule public TestName name = new TestName();

@Test 
public void test() {
    assertEquals("test", name.getMethodName());
}