I have a problem in defining bearer token in restTemplate.getForObject in OrderServiceImpl and OrderServiceImplTest of order service. The problem is located at getOrderDetails of OrderServiceImpl , test_When_Order_Success and test_When_Get_Order_NOT_FOUND_then_Not_Found of OrderServiceImplTest.
Here is the code snippets shown below.
@Override
public OrderResponse getOrderDetails(long orderId, String bearerToken) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+ bearerToken);
// How can I add bearer token in here
ProductResponse productResponse
= restTemplate.getForObject(
"http://PRODUCT-SERVICE/product/" + order.getProductId(),
ProductResponse.class
);
// How can I add bearer token in here
PaymentResponse paymentResponse
= restTemplate.getForObject(
"http://PAYMENT-SERVICE/payment/order/" + order.getId(),
PaymentResponse.class
);
....
}
Here is the test method shown below.
@DisplayName("Get Order - Success Scenario")
@Test
void test_When_Order_Success() {
String bearerToken = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+ bearerToken);
//Mocking
Order order = getMockOrder();
when(orderRepository.findById(anyLong()))
.thenReturn(Optional.of(order));
when(restTemplate.getForObject(
"http://PRODUCT-SERVICE/product/" + order.getProductId(),
ProductResponse.class
)).thenReturn(getMockProductResponse());
when(restTemplate.getForObject(
"http://PAYMENT-SERVICE/payment/order/" + order.getId(),
PaymentResponse.class
)).thenReturn(getMockPaymentResponse());
//Actual
OrderResponse orderResponse = orderService.getOrderDetails(1,bearerToken);
//Verification
verify(orderRepository, times(1)).findById(anyLong());
verify(restTemplate, times(1)).getForObject(
"http://PRODUCT-SERVICE/product/" + order.getProductId(),
ProductResponse.class);
verify(restTemplate, times(1)).getForObject(
"http://PAYMENT-SERVICE/payment/order/" + order.getId(),
PaymentResponse.class);
//Assert
assertNotNull(orderResponse);
assertEquals(order.getId(), orderResponse.getOrderId());
}
How can I define bearer token in these methods?
Here is the OrderServiceImpl: Link
Here is the OrderServiceImplTest: Link
The getForObject() method of RestTemplate does not support headers. You should use the exchange() method provided by the RestTemplate class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.