如何在 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 Methode 中创建类中所有测试方法都使用的对象。

如果您的某个测试确实需要一个仅在该处使用的对象,则该测试应自行实例化该对象。

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

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

,

如果我们需要知道当前将在@Before 方法中执行哪个@Test 方法, 这可以使用@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
    
}