在 Java 的 ifPresent() 中使用 AssertJ 的 assertThat 函数 可选

Use assertThat function of AssertJ in ifPresent() of Java Optional

如何删除 ifPresent()assertThat 的 try-catch 块?编译器只给我一个在 ifPresent() 中使用 assertThat 的选项,即用 try-catch 块包围它。再次抛出异常也是不允许的。

@Test
public void testPostRequestThenSaveResponse()
        throws HttpStatusCodeException, JsonProcessingException, IllegalArgumentException, IOException {
    // Should success.
    try {
        ServiceAssignmentImpl.httpPostDeliveryOrder(url, token, sod, customerSite, customer, item, uom, driver)
                .ifPresent((deliveryOrderResponse) -> {
                    // increase DO number for next test.
                    deliveryOrderNum++;
                    DeliveryOrderResponse savedDOResponse = deliveryOrderResponseRepository
                            .save(deliveryOrderResponse);
                    DeliveryOrderResponse fetchedDOResponse = deliveryOrderResponseRepository
                            .findOne(savedDOResponse.getId());                      
                    try {
                        assertThat(json.write(fetchedDOResponse))
                                .isEqualTo(objectMapper.writeValueAsString(deliveryOrderResponse));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                });
    } catch (HttpStatusCodeException e) {
        // need getResponseBodyAsString() to see detail error message.
        System.out.println("** HttpStatusCodeException: " + e.getResponseBodyAsString());
        throw e;
    }
}

只需使用 .get(),如果响应不存在,您的测试应该不会通过,因此无需使其成为条件。

我已经在没有 MCVE 的情况下尽可能地调整了你的代码。

    @Test
    public void testPostRequestThenSaveResponse()
            throws HttpStatusCodeException, JsonProcessingException, IllegalArgumentException, IOException {
        // Should success.
        try {
            var = deliveryOrderResponseServiceAssignmentImpl.httpPostDeliveryOrder(url, token, sod, customerSite, customer, item, uom, driver).get()
                   
             // increase DO number for next test.
             deliveryOrderNum++;
             DeliveryOrderResponse savedDOResponse = deliveryOrderResponseRepository
                                .save(deliveryOrderResponse);
             DeliveryOrderResponse fetchedDOResponse = deliveryOrderResponseRepository
                                .findOne(savedDOResponse.getId());  
             assertThat(json.write(fetchedDOResponse))
                                    .isEqualTo(objectMapper.writeValueAsString(deliveryOrderResponse));
                     
        } catch (HttpStatusCodeException e) {
            // need getResponseBodyAsString() to see detail error message.
            System.out.println("** HttpStatusCodeException: " + e.getResponseBodyAsString());
            throw e;
        }
    }