Registration API integration test

We haven't added any integration test to our application yet. Let's create one for the registration API as an example. To keep the integration tests separate from the unit tests, we will put all the integration tests inside the src/test/java/integration package, and name these tests with the suffix IntegrationTests.

The following is what the register_existedUsername_shouldFailAndReturn400() test method in RegistrationApiIntegrationTests looks like:

...
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,
classes = TaskAgileApplication.class)
@ActiveProfiles("test")
@AutoConfigureMockMvc
public class RegistrationApiIntegrationTests {

@Autowired
private MockMvc mvcMock;

@Test
public void register_existedUsername_shouldFailAndReturn400() throws
Exception {
RegistrationPayload payload = payload("exist",
"[email protected]");
mvcMock.perform(
post("/api/registrations")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtils.toJson(payload)))
.andExpect(status().is(201));

// Try to register again with the same username
RegistrationPayload payload2 = payload("exist",
"[email protected]");
mvcMock.perform(
post("/api/registrations")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtils.toJson(payload2)))
.andExpect(status().is(400))
.andExpect(jsonPath("$.message").value("Username already
exists"));
}
...
}

As you can see, this test is also written as a unit test, very similar to the RegistrationApiControllerTests. The biggest difference is that, in this test, we use the @SpringBootTest annotation to start the entire application, whereas in RegistrationApiControllerTests, we used the @WebMvcTest annotation to focus only on the tests of Spring MVC components. In this test, we do not need to provide a @MockBean of UserService, because Spring will initialize the actual UserServiceImpl in the container.

In the register_existedUsername_shouldFailAndReturn400() method, instead of mocking the behavior of UserService to throw UsernameExistsException, we call the registration API to create a user first and then call the API with the same username. In this test, the first user will be saved into the H2 database. The second API call will cause the throw of UsernameExistException. There is no mocked behavior in the test. That's why it is an integration test.

The following screenshot shows the commit record of this integration test:

Figure 15.2: Commit record of the integration test
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.147.77