如何知道Junit 4中@before方法中的当前@Test方法



我在JUnit测试类中有以下代码。如何知道在@Before方法中,哪个@Test方法现在要执行。因为@Before方法在@Test方法之前被调用。我想在@Before中编写代码,这样它将为相应的@Test Method设置相关的测试数据。

/*
* @Before is called before executing each test method.
* We are using it to setup test data before executing test case
* */
@Before
public void prepareForTest()throws Exception{
System.out.println("prepareForTest called");
}

/**
* This method to check sub requirements are present 
* 1. AssertNotNull variant
* 2. Condition that MapList is not empty 
*/
@Test
public void testGetSubRequirementNotNull()throws MatrixException{
System.out.println("testGetSubRequirementNotNull called");

String strReqObjectId = propertySet.getProperty("Requirement.testGetSubRequirementNotNull.objectId");

RequirementService reqService = serviceFactory.getRequirementService(context);
MapList mlSubReqList = reqService.getSubRequirement(context, strReqObjectId);

assertNotNull("SubRequirement List is null", mlSubReqList);
assertFalse("SubRequirement list is empty", mlSubReqList.isEmpty());

}

/**
* This method is to check sub requirements are not present
* 1. AssertNull variant
* 2. Condition that MapList is empty 
*/
@Test
public void testGetSubRequirementNull()throws MatrixException{
System.out.println("testGetSubRequirementNull called");

String strReqObjectId = propertySet.getProperty("Requirement.testGetSubRequirementNotNull.objectId");

RequirementService reqService = serviceFactory.getRequirementService(context);
MapList mlSubReqList = reqService.getSubRequirement(context, strReqObjectId);

assertNull("SubRequirement List is not null", mlSubReqList);
assertTrue("SubRequirement list is not empty", mlSubReqList.isEmpty());

}

@Before的文档说:

在编写测试时,通常会发现几个测试在运行之前需要创建类似的对象。

根据我的经验,你应该只在你的@Before方法中创建被你的类中的所有测试方法使用的对象。

如果你的一个测试确实需要一个只在那里使用的对象,测试应该自己实例化这个对象。

如果几个(不是全部)测试需要相同(或类似)的对象,我建议在每个测试方法调用的类的private助手方法中提取对象的实例化。这也将遵循DRY原则。

tl;博士;
我认为您不需要知道接下来将执行哪个测试。每个Test都应该实例化它自己需要的对象。

如果我们需要知道哪个@Test方法当前将在@Before方法中执行,这在技术上可以像下面这样使用@Rule TestName字段来实现。

@Rule public TestName testName = new TestName();
/*
* @Before is called before executing each test method.
* This method is called before executing testGetSubRequirement method.
* We are using it to setup test data before executing test case
* */
@Before
public void prepareForTest()throws Exception{
System.out.println("prepareForTest called::"+testName.getMethodName());//it will print name of @Test method to be excuted next

}

最新更新