java - 在 JUnit 测试中强行抛出异常
问题描述
我打算增加代码覆盖率。在此过程中,我无法测试特定方法的 catch 块。我试图强制方法调用出现异常。
RuleSchedule.java
public class RuleScheduler
{
private boolean enabled;
private Integer batchSize;
@Autowired
private ExternalService externalService;
public void executeRuleValidation()
{
if (enabled)
{
try
{
StopWatch stopWatch = new StopWatch();
stopWatch.start();
externalService.executeRuleValidationForProposal(batchSize);
stopWatch.stop();
log.info("Total time taken for RuleValidation:{} for batchSize :{}",
stopWatch.getTotalTimeSeconds(), batchSize);
}
catch (Exception ex)
{
// System.out.println("~~~~~~CATCH~~~~~~");
log.error("Rule exception :{}", ex);
}
}
}
}
我正在尝试不同的方法来引发异常以进入上述代码的 catch 块,但无法这样做。这是我的测试课。甚至批量大小也接受空值。
RuleScheduleTest.java
@RunWith(MockitoJUnitRunner.class)
public class RuleSchedulerTest
{
@Mock
private ExternalService externalService;
@InjectMocks
private RuleScheduler RuleScheduler;
@Before
public void init()
{
ReflectionTestUtils.setField(RuleScheduler, "enabled", true);
ReflectionTestUtils.setField(RuleScheduler, "batchSize", 5);
}
@Test
public void testExecuteRuleValidation()
{
RuleScheduler.executeRuleValidation();
}
}
解决方案
一种可能性是配置您的模拟externalService
实例以引发异常。然后,您应该能够验证与模拟的交互。类似于以下内容:
@Test
public void testExecuteRuleValidation(){
// configure your mock 'externalService' instance to throw an exception
when(externalService.executeRuleValidationForProposal(any(Integer.class))).thenThrow(IllegalArgumentException.class);
RuleScheduler.executeRuleValidation();
// now verify mock interaction
verify(externalService, times(1)).executeRuleValidationForProposal(any(Integer.class));
}
推荐阅读
- azure - 数据工厂中的复制数据问题
- html - 我如何在 html 中创建一个表,第一行只有 1 列,其他行超过 1
- numpy - numpy数组中的间距
- java - 如何设置 android studio 材质滑块的样式
- sql-server - Docker 容器应用程序中的 EF Core SQL 数据库连接错误
- apache-kafka - SpoolDir Kafka 连接器 - 错误处理程序中超出了容差
- typescript - 如果验证失败,如何设置后备值(NestJS,类验证器)
- bash - 将函数添加到 bash 脚本导致错误
- python - 为什么我无法从线程聊天中获取文本?
- javascript - 为传单路由机导入大量 JSON 坐标