如何在JUnit父类setUp方法中获取子类测试方法元数据?
在JUnit @Before方法中获取当前测试方法元数据的实现方案
这个需求完全可以实现,既可以通过JUnit原生API直接获取,也能借助Spring TestContext拿到测试方法的元数据,以下是具体实现方式:
方案一:使用JUnit原生TestName参数注入
JUnit本身支持在@Before、@After等生命周期方法中注入TestName对象,通过它可以直接获取当前要执行的测试方法名,无需依赖Spring的额外API:
修改ContractTestRunner的setUp方法,添加TestName参数:
@RunWith(SpringRunner.class) @SpringBootTest public class ContractTestRunner { @MockBean MessageRepository messageRepository; @Before public void setUp(TestName testName) { // 获取当前测试方法名 String currentTestMethodName = testName.getMethodName(); // 根据方法名执行特定逻辑 if ("whenPageable_isNotNull_shouldReturnList".equals(currentTestMethodName)) { given(messageRepository.findAll(any(Pageable.class))).willReturn(new PageImpl<>(Collections.emptyList())); } else if ("whenPageable_isNull_shouldThrowException".equals(currentTestMethodName)) { given(messageRepository.findAll(null)).willThrow(IllegalArgumentException.class); } } }
JUnit会自动将当前测试方法的元数据注入到TestName参数中,这种方式简单直接,不需要额外配置。
方案二:借助Spring TestContext获取方法元数据
如果需要更完整的测试上下文信息,可以通过Spring的TestContext对象获取当前测试方法的Method实例,进而拿到方法名、注解等更多元数据:
首先在ContractTestRunner中注入TestContext,然后在setUp方法中获取测试方法:
@RunWith(SpringRunner.class) @SpringBootTest public class ContractTestRunner { @MockBean MessageRepository messageRepository; @Autowired private TestContext testContext; @Before public void setUp() throws Exception { // 获取当前测试方法的Method对象 Method currentTestMethod = testContext.getTestMethod(); String methodName = currentTestMethod.getName(); // 同样可以根据方法名执行特定逻辑 switch (methodName) { case "whenPageable_isNotNull_shouldReturnList": given(messageRepository.findAll(any(Pageable.class))).willReturn(new PageImpl<>(Collections.emptyList())); break; case "whenPageable_isNull_shouldThrowException": given(messageRepository.findAll(null)).willThrow(IllegalArgumentException.class); break; } } }
这种方式能获取到测试方法的完整反射信息,适合需要读取方法注解、参数类型等更复杂场景的需求。
注意事项
- 由于
MessageTests继承自ContractTestRunner,父类中修改的setUp方法会自动作用于所有子类的测试方法,无需修改自动生成的子类代码。 - 两种方案都能正常工作,选择哪种取决于你是否需要Spring测试上下文的额外信息。
内容的提问来源于stack exchange,提问作者Yarik Soltys
相关产品推荐
相关产品推荐

