我跟随本教程创建了一个电子商务微服务体系结构(法语),现在我正在尝试编写一些测试。我的体系结构由4个微服务和Eureka和Zuul组成:
支付微型服务必须调用订单微服务来检查订单是否已经支付。这是我无法复制来编写单元测试的东西。我想在不启动订单微服务的情况下测试这个微服务。
我如何在不启动订单微服务的情况下测试它?
我已经为订单、微服务和产品微服务编写了一些测试。
以下是付款主计长:
/*
* Operations to save a payment and notify the orders microservice to update the status of the sayed oreder
**/
@PostMapping(value = "/payment")
public ResponseEntity<Payment> payAnOrder(@RequestBody Payment payment){
// We verify if the order has been already payed
System.out.println("We verify if the order has been already payed");
Payment existingPayment = paymentDao.findByidOrder(payment.getIdOrder());
if(existingPayment != null) throw new ExistingPaymentException("This order has already been payed!");
// We save the payment
System.out.println("We save the payment");
Payment newPayment = paymentDao.save(payment);
// if the DAO return null, there was a problem when saving the payment
System.out.println("if the DAO return null, there was a problem when saving the payment");
if(newPayment == null) throw new ImpossiblePaymentException("Error, impossible to establish the payment, retry later!");
// We retrieve the order corresponding to that payment by calling orders microservice
System.out.println("We retrieve the order corresponding to that payment by calling orders microservice");
Optional<OrderBean> orderReq = microserviceOrderProxy.retrieveOneOrder(payment.getIdOrder());
// orderReq.get() extract the object of type OrderBean from Optional
System.out.println("orderReq.get() extract the object of type OrderBean from Optional");
OrderBean order = orderReq.get();
// We update the object to mak the order as payed
System.out.println("We update the object to mak the order as payed");
order.setOrderPayed(true);
// We send the object updated to the orders microservice to update the order's status
System.out.println("We send the object updated to the orders microservice to update the order's status");
microserviceOrderProxy.updateOrder(order);
// We return 201 CREATED to notify the client that the payment has been registered
System.out.println("We return 201 CREATED to notify the client that the payment has been registered");
return new ResponseEntity<Payment>(newPayment, HttpStatus.CREATED);
}在我们检索与付款相对应的订单的步骤中,我被阻塞了,因为它试图调用orders微服务,但它没有运行!
下面是完整的代码:微服务
发布于 2019-04-04 12:16:47
您可以轻松地模拟在单元测试中调用的其他微服务。在Mockito (捆绑在spring-boot-starter-test中)中,您可以使用以下方法来完成这一任务:
public class PaymentControllerTest {
private PaymentController controller;
@Mock
private MicroserviceOrderProxy microserviceOrderProxy;
... other mocks here
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
controller = new PaymentController(microserviceOrderProxy, ...);
}
@Test
public void exampleTest() {
Mockito.when(microserviceOrderProxy.updateOrder(Mockito.any())).thenReturn(--mocked result here--);
...
}
}https://stackoverflow.com/questions/55491107
复制相似问题