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

use*_*111 5 java junit

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

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

    @Test
    public void exampleTest()
    {
        //Some code here.
    }
 }
Run Code Online (Sandbox Code Playgroud)

Jay*_*tel 19

作为讨论在这里,请尝试使用@rule和测试名称组合.

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

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

以下是使用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 ...");
    }
}
Run Code Online (Sandbox Code Playgroud)