Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is one suggestion that should give you some ideas. I assume that you are familiar with the <code>SpringJUnit4ClassRunner</code> and the <code>@ContextConfiguration</code>. Start by creating an test application context that contains <code>PcUserController</code> and a mocked <code>PcUserService</code>. In the example <code>PcUserControllerTest</code> class below, Jackson is used to convert JSON messages and Mockito is used for mocking. </p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(/* Insert test application context here */) public class PcUserControllerTest { MockHttpServletRequest requestMock; MockHttpServletResponse responseMock; AnnotationMethodHandlerAdapter handlerAdapter; ObjectMapper mapper; PcUser pcUser; @Autowired PcUserController pcUserController; @Autowired PcUserService pcUserServiceMock; @Before public void setUp() { requestMock = new MockHttpServletRequest(); requestMock.setContentType(MediaType.APPLICATION_JSON_VALUE); requestMock.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); responseMock = new MockHttpServletResponse(); handlerAdapter = new AnnotationMethodHandlerAdapter(); HttpMessageConverter[] messageConverters = {new MappingJacksonHttpMessageConverter()}; handlerAdapter.setMessageConverters(messageConverters); mapper = new ObjectMapper(); pcUser = new PcUser(...); reset(pcUserServiceMock); } } </code></pre> <p>Now, we have all the code needed to create the tests:</p> <pre><code>@Test public void shouldGetUser() throws Exception { requestMock.setMethod("GET"); requestMock.setRequestURI("/pcusers/1"); when(pcUserServiceMock.read(1)).thenReturn(pcUser); handlerAdapter.handle(requestMock, responseMock, pcUserController); assertThat(responseMock.getStatus(), is(HttpStatus.SC_OK)); PcUser actualPcUser = mapper.readValue(responseMock.getContentAsString(), PcUser.class); assertThat(actualPcUser, is(pcUser)); } @Test public void shouldCreateUser() throws Exception { requestMock.setMethod("POST"); requestMock.setRequestURI("/pcusers/create/1"); String jsonPcUser = mapper.writeValueAsString(pcUser); requestMock.setContent(jsonPcUser.getBytes()); handlerAdapter.handle(requestMock, responseMock, pcUserController); verify(pcUserServiceMock).create(pcUser); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload