Hopefully most of this code speaks for itself
-
- Posts: 190
- Joined: Wed Dec 18, 2024 6:41 am
Hopefully most of this code speaks for itself
when(orderRepositoryMock.save(any(Order.class))).thenReturn(added);
mockMvc.perform(post("/hello-camel/1.0/order")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(order)))
.andExpect(status().isOk())
.andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", is(1)))
.andExpect(jsonPath("$.customerId", is(1)))
.andExpect(jsonPath("$.orderItems[0].id", is(2)))
.andExpect(jsonPath("$.orderItems[0].inventoryItemId", is(1)))
.andExpect(jsonPath("$.orderItems[0].quantity", is(100)))
.andExpect(jsonPath("$.orderItems[1].id", is(3)))
.andExpect(jsonPath("$.orderItems[1].inventoryItemId", is(2)))
.andExpect(jsonPath("$.orderItems[1].quantity", is(50)));
ArgumentCaptor<Order> orderCaptor = ArgumentCaptor.forClass(Order.class);
verify(orderRepositoryMock, times(1)).save(orderCaptor.capture());
verifyNoMoreInteractions(orderRepositoryMock);
Order orderArgument = orderCaptor.getValue();
assertNull(orderArgument.getId());
assertThat(orderArgument.getCustomerId(), is(1L));
assertEquals(orderArgument.getOrderItems().size(), 2);
}
}
<span class="copy">Copy</span>
. Here are some pointers:
The WebMvcTest(OrderController.class) annotation ensures that you can test the OrderController in isolation. With this guy you can autowire a MockMvc instance that basically has all you need to unit test a controller;
The controller has a dependency on the OrderRepository , which we will mock in this unit test using the @MockBean annotation;
We first use some helper builder classes to fluently build our test Order instances;
Next we configure our mock repository to return a full fledged special lead Order object when the save method is called with an Order argument;
Now we can actually POST an Order object to our controller and test the JSON being returned;
Next check is whether the mock repository was called and ensure that is was called only once;
Finally we check the Order POJO that was sent to our mock repository.
Running the test will show us we build a high quality controller here. There's also a unit test available for the GET method. You can view it on GitHub. The GET method is a lot easier to unit test, so let's skip it to keep this blog post from getting too verbose.
Testing the Camel route
Now for the most interesting part. We want to test the Camel route we built in our previous blog post . Let's first revisit it again:
?
There's a lot going on in this route. Ideally I would like to perform two tests:
One to check if the XML consumed from the ftp endpoint is being properly unmarshalled to an Order POJO;
One to check the quality of the subsequent marshalling of said POJO to JSON and also to check if it's being sent to our REST controller.
So let's split our route into two routes to reflect this.