测试RepositorSpring Boot Integration Test-模拟返回null

问题描述

我无法对SpringBoot应用程序进行集成测试。

这是我的课程的基本结构:

@Controller
@RequiredArgsConstructor
public class PushNotificationController {
    private final PushNotificationService pnSvc;
    private final PushNotificationRepository pnRepo;
    private final DeviceTokenRepository dtRepo;

/**
 * This method sends all PushNotifications from memory,* which are not sent yet.
 */
public List<MiddlemanResponse> send() {
    List<MiddlemanResponse> middlemanResponses = pnSvc.sendAll(dtRepo.findBySendStatus(DeviceTokenEntity.Status.SCHEDULED));

    return middlemanResponses;
}

}

如您所见,它取决于两个存储库,它们是从JpaRepository扩展的接口和一个Service-class。它们都是通过lombok RequiredAllArgs-constructor注入的。

在测试中,我正在与可以正常工作的H2数据库进行通信,并且我还想模拟pnSvc

这是我的测试班:

@RunWith(SpringRunner.class)
@SpringBootTest
public class PushNotificationControllerIntegrationTest {
@Autowired
private PushNotificationController underTest;

@Autowired
private DeviceTokenRepository dtRepo;
@Autowired
private PushNotificationRepository pnRepo;
@MockBean //we mock this dependency because we dont want to send actual notifications
private PushNotificationService pnSvc;

//testvalues
private final Long FIRST_PUSH_NOTIFICATION_ID = 1L;
private final Long FIRST_DEVICE_TOKEN_ID = 1L;
PushNotificationEntity pushNotification = new PushNotificationEntity(FIRST_PUSH_NOTIFICATION_ID,"message","customString",1L,"metadata");
DeviceTokenEntity deviceToken = new DeviceTokenEntity(FIRST_DEVICE_TOKEN_ID,"deviceToken",pushNotification,DeviceTokenEntity.Platform.IPHONE,"applicationType","brandId",DeviceTokenEntity.Status.SCHEDULED);

@Before
public void setUp() throws MiddlemanException {
    when(pnSvc.sendAll(dtRepo.findBySendStatus(DeviceTokenEntity.Status.SCHEDULED))).thenReturn(List.of(new MiddlemanResponse(deviceToken,"response_message")));

    pnRepo.save(pushNotification);
    dtRepo.save(deviceToken);
}

@Test
public void sendOneSuccessTest() {
    List<MiddlemanResponse> responses = underTest.send();

    assertEquals(1,responses.size());
}

}

不幸的是,模拟的方法pnSvc.sendAll(...)返回null,因此MiddlemanResponse列表为空,并且我的测试失败,并显示以下信息:

org.opentest4j.AssertionFailedError: expected: <1> but was: <0>
Expected :1
Actual   :0

我希望模拟方法应返回设置值List.of(new MiddlemanResponse(deviceToken,"response_message")

解决方案 感谢dbl和Gianluca Musa的答复,我采用了Gianluca Musa的使用any()而不是传递实际参数的方法 -> pnSvc.sendAll(any())模拟响应时

我也没有使用詹卢卡·穆萨建议的org.mockito.Matchers.any 而是org.mockito.Mockito.any,因为它不推荐使用。

解决方法

错误可能是模拟过滤器不正确,您可以使用通用选择器来模拟sendAll(),请尝试

when(pnSvc.sendAll(org.mockito.Mockito.any()).thenReturn(List.of(new MiddlemanResponse(deviceToken,"response_message")));

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...