【问题标题】:Get the name of currently executing @Test method in @Before in JUNIT [duplicate]获取JUNIT中@Before中当前正在执行的@Test方法的名称[重复]
【发布时间】:2013-06-18 07:11:54
【问题描述】:

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

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

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

【问题讨论】:

标签: java junit


【解决方案1】:

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

根据documentation before 方法应该有测试名称。

注释包含规则的字段。这样的字段必须是公共的,而不是 静态的,是 TestRule 的子类型。该声明传递给 TestRule 将运行任何 Before 方法,然后是 Test 方法,然后 finally 任何 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 ...");
    }
}

【讨论】:

    【解决方案2】:

    尝试在org.junit.rules.TestName 类中使用@Rule 注释

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

    【讨论】:

      猜你喜欢
      • 2013-06-18
      • 2023-03-10
      • 2010-10-03
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 2012-11-16
      相关资源
      最近更新 更多