在 java 单元测试中,使用 @repeatedtest 注解可以指定某个测试方法重复执行指定的次数。该注解位于 org.junit.jupiter.api 包下,是 junit 5 提供的功能。通过在测试方法上添加 @repeatedtest(次数),junit 会在运行该测试时自动循环调用该方法多次,每次执行都会获得一个新的 repetitioninfo 实例,可用于获取当前是第几次执行以及总共有多少次执行。

如何配置重复执行的次数
配置重复执行次数非常简单,只需在测试方法上方添加 @RepeatedTest 注解并传入一个整数参数即可。例如,@RepeatedTest(5) 表示该测试方法将连续执行 5 次。如果未指定参数,默认值为 1,即只执行一次。这种机制常用于需要验证稳定性、处理随机数据或进行压力测试的场景。

import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.TestInfo; import static org.junit.jupiter.api.Assertions.assertTrue; public class RepeatedTestExample { @RepeatedTest(3) void testWithFixedCount(TestInfo testInfo) { int current = testInfo.getRepetitionInfo().getCurrentRepetition(); int total = testInfo.getRepetitionInfo().getTotalRepetitions(); System.out.println("Running repetition " + current + " of " + total); assertTrue(current >= 1 && current <= total); } }如何使用动态名称标识每次执行
为了让测试结果更清晰,可以在 @RepeatedTest 注解中使用占位符来生成动态的测试名称。支持两种占位符:{currentRepetition} 表示当前是第几次执行,{totalRepetitions} 表示总共要执行多少次。这样在测试报告或控制台输出中,每次执行都会有独立的、易于区分的名称,方便定位问题。
立即学习“Java免费学习笔记(深入)”;

import org.junit.jupiter.api.RepeatedTest; import static org.junit.jupiter.api.Assertions.assertEquals; public class DynamicNameExample { @RepeatedTest(value = 4, name = "Check iteration {currentRepetition} of {totalRepetitions}") void testWithDynamicName() { assertEquals(4, 2 + 2); } }基于 TestInfo 获取当前执行状态的具体问题
当需要在测试逻辑内部知道当前是第几次执行时,可以将 RepetitionInfo 或 TestInfo 作为参数注入到测试方法中。通过 TestInfo.getRepetitionInfo() 可以获取 RepetitionInfo 对象,进而调用 getCurrentRepetition() 和 getTotalRepetitions() 方法获取具体数值。这在需要根据执行次数改变行为或记录日志时非常有用。


















