测试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,因为它不推荐使用。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)