You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

这段JUnit测试代码是否与数据库交互?我的判断是否正确?

问题

有人问我这段测试代码是否会连接数据库,因为没找到@Mock或@MockBean注解,我判断它会从真实数据库获取数据——这个判断正确吗?

对应的测试代码如下:

@DisplayName("Given an existing vacation with updated data have same type of the existing vacation when invoking updatedExistingVacation then vacation is updated successfully")
void givenUpdatedVacationWithSameType_whenUpdateExistingVacation_thenVacationIsUpdatedSuccessfully() {
//GIVEN

final Vacation existingVacation = VacationFixture.getVacation();

final Vacation updateVacation = VacationFixture.getUpdatedVacationWithSameType();

final UpdateVacationDTO updateVacationDTO = VacationMapper.INSTANCE.toUpdateVacationDTO(updateVacation);

when(vacationRepository.findById(updateVacation.getId())).thenReturn(Optional.of(existingVacation));

when(vacationRepository.save(updateVacation)).thenReturn(updateVacation);

//WHEN

final VacationResponseDTO updatedVacation = classUnderTest.updateExistingVacation(updateVacationDTO);
//THEN

assertThat(updatedVacation.getId()).isEqualTo(updateVacation.getId());

verify(vacationRepository, times(1)).save(updateVacation);

}
回答

你的判断不正确。

虽然代码里没直接写@Mock或@MockBean,但从when(vacationRepository.findById(...)).thenReturn(...)和verify(vacationRepository, times(1)).save(...)这些调用能明确看出,vacationRepository是Mockito框架生成的Mock实例,不会连接真实数据库:

  • when(...).thenReturn(...)是在预设Mock对象的方法返回值,这里直接返回了VacationFixture生成的模拟数据,完全不涉及真实数据库查询;
  • verify(...)是验证Mock对象的方法是否被调用了指定次数,同样和真实数据库操作无关。

这类测试属于单元测试,核心就是通过Mock依赖(比如这里的Repository)隔离外部资源,只聚焦测试业务逻辑本身,不会产生真实的数据库读写行为。

内容的提问来源于stack exchange,提问作者Amy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 03:40:00