簡體   English   中英

測試 RepositorSpring Boot 集成測試 - 模擬返回 null

[英]Testing RepositorSpring Boot Integration Test - mock returns 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 和一個服務類擴展的接口。 所有這些都是通過 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(...)方法pnSvc.sendAll(...)返回null ,因此 MiddlemanResponse 列表為空,我的測試失敗:

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

我的期望是List.of(new MiddlemanResponse(deviceToken, "response_message")方法應該返回設置值List.of(new MiddlemanResponse(deviceToken, "response_message")

解決方案感謝 dbl 和 Gianluca Musa 的回復,我采用 Gianluca Musa 的方法,在pnSvc.sendAll(any())響應時使用 any() 而不是傳遞實際參數 -> pnSvc.sendAll(any())

我也沒有使用 Gianluca Musa 提議的org.mockito.Matchers.any而是org.mockito.Mockito.any因為它的棄用。

大概錯誤是mock的filter不對,可以用一個泛型選擇器來模擬sendAll(),試試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM