#WithMockUser make my tests work even when I don't pass the header - spring

I am working on an API with an API Key authentication (X-API-KEY/VALUE) and its works fine. My issue is in the unit test. When I am using #WithMockUser on the Controller test slice I am testing with #WebMvcTest, the tests works fine even when I don't add the header in the mockMvc test.
I would like to know what is the best way to test it?
#Test
#WithMockUser
void givenController_whenFindingResult_thenReturnResultWithStatus_200() throws Exception {
when(service.findResultDescriptionsByLanguage(anyString())).thenReturn(TestData.getSampleResultDescriptions());
mockMvc.perform(get(TestData.API_V1_BASE_URL + "/descriptions/{language}", "en")
.header(apiKeyProperties.getHeaderName(), apiKeyProperties.getApiKey())
.contentType(MediaType.APPLICATION_JSON))
.andExpectAll(
status().isOk(),
jsonPath("$.statusValue", is(HttpStatus.OK.value())),
jsonPath("$.statusReasonPhrase", is(HttpStatus.OK.getReasonPhrase())),
jsonPath("$.description", containsString("Descriptions found for en"))
);
}

Related

How to do integration tests with mocked service

I'm working at a small parking service REST API.
For example I have endpoint:
#RequestMapping("/departure")
public ResponseEntity<String> departure(#RequestBody CarAtGateModel carAtGateModel) throws Exception {
return parkingService.carDeparture(carAtGateModel.getCarEntity().getIdCar());
}
method parkingService.carDeparture looks like this:
public ResponseEntity<String> carDeparture(String carID) throws UnidentifiedCarException {
CarAndParkingIDsEntity carAndParkingIDsEntity = carAndParkingIDsRepository.findByIdCar(carID);
if (carAndParkingIDsEntity == null) {
throw new UnidentifiedCarException();
} else {
carAndParkingIDsEntity.setIdParking("-1");
carAndParkingIDsRepository.flush();
return new ResponseEntity<>("Gate up", HttpStatus.OK);
}
}
And the problem is when I'm trying to do some integration tests. Unit tests for parking service pass correctly but I don't know exactly what should I do for integration tests.
I was thinking about something like. Mock carAtGateModel (it's carId and ParkingId) and send it to the endpoint and then mock parkingservice because I'm using it inside and I don't want to change data in the database.
when(parkingService.carDeparture(anyString())).thenReturn(new ResponseEntity<>("Gate up",
HttpStatus.OK));
HttpEntity<CarAtGateModel> request = new HttpEntity<>(carAtGateModel);
ResponseEntity<String> response = testRestTemplate.postForEntity("/departure", request,
String.class);
I would suggest you use #WebMvcTest instead to have a slice test (sort of integration test that focuses on a single application layer).
#ExtendWith(SpringExtension.class)
#WebMvcTest(YourController.class)
public class YourControllerIntegrationTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private ParkingService parkingService;
// Your test cases here
}
You would use mockMvc to perform an actual call to the REST endpoint with an actual CarAtGateModel object as JSON in the request body. You would also mock the behaviour of your ParkingService, thus focusing the test on your Controller.

How to write junit test cases for below exception handling code?

#PostMapping("/addCompany")
public Company createCompany(#Valid #RequestBody Company company, Errors errors) {
if (errors.hasErrors()) {
throw new ValidationException(errors.getFieldError().getDefaultMessage());
}
return companyService.addCompany(company);
}
You can test it in two ways:
unit test of controller
web layer test
Unit test:
Mock Errors and call createCompany with that mock as an argument.
Verify that exception is thrown
Web layer test:
post an invalid request with mockMvc
check that error code is returned
#WebMvcTest(CompanyController.class)
class CompanyControllerTest {
private static final String CREATE_COMPANY_ENDPOINT = "/addCompany/";
#Autowired
private MockMvc mockMvc;
#Test
void respondsWith4xxOnInvalidCreateCompanyRequest() throws Exception {
String invalidRequest = "{\"id\":\"aaa\", \"name\":\"bbb\"}"
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders
.post(CREATE_COMPANY_ENDPOINT)
.content(invalidRequest)
.contentType(MediaType.APPLICATION_JSON_VALUE);
this.mockMvc.perform(builder)
.andExpect(status().is4xxClientError());
}
}
In this case, I have a strong preference to web layer test - you check actual validation logic. Mocking Errors buys you nothing except code coverage.
On top of that:
Your handling of validation errors is trivial. If you drop Errors from the parameter list, on invalid input Spring will throw MethodArgumentNotValidException with BindingResult, which has all the data you need.

How can i check if each object in an array has a specific property exists using spring junit integration test?

I am writing a spring integration test for a method in my resource class . accessing the resource method returns a json response . I would like do an assertion .
the following is my test method.
#Test
public void testGetPerformanceCdrStatusesByDateRangeAndFrequencyMonthly() throws Exception {
this.restMvc.perform(MockMvcRequestBuilders.get(
"/api/performance/cdrStatus?startDate=2019-09-01T00:00:00.000Z&endDate=2019-09-30T23:59:59.999Z&frequency=PER_MONTH"))
.andDo(print()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses").exists())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses").isArray())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses").isNotEmpty());
}
the response is as follows
{"histogramDistributionbyCdrStatuses":[{"dateRange":"2019-09","total":19,"delivered":7,"undeliverable":4,"expired":4,"enroute":4}]}
the assertion i want to do is each object in the array histogramDistributionbyCdrStatuses has field dateRange, total , delivered , undeliverable , expired and enroute exists.
how can i do it . I am also ok to use hamcrest matchers.
really appreciate any help
I just extended my test as follow and it works
#Test
public void testGetPerformanceCdrStatusesByEnrouteStatus() throws Exception {
this.restMvc.perform(MockMvcRequestBuilders.get(
"/api/performance/cdrStatus?startDate=2019-09-01T00:00:00.000Z&endDate=2022-12-31T23:59:59.999Z&frequency=PER_DAY"))
.andDo(print()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses").exists())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses").isArray())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses").isNotEmpty())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses.[*].dateRange").exists())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses.[*].total").exists())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses.[*].delivered").exists())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses.[*].undeliverable").exists())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses.[*].expired").exists())
.andExpect(jsonPath("$.histogramDistributionbyCdrStatuses.[*].enroute").exists());
}

Cannot properly test ErrorController Spring Boot

due to this tutorial - https://www.baeldung.com/spring-boot-custom-error-page I wanted to customize my error page ie. when someone go to www.myweb.com/blablablalb3 I want to return page with text "wrong url request".
All works fine:
#Controller
public class ApiServerErrorController implements ErrorController {
#Override
public String getErrorPath() {
return "error";
}
#RequestMapping("/error")
public String handleError() {
return "forward:/error-page.html";
}
}
But I dont know how to test it:
#Test
public void makeRandomRequest__shouldReturnErrorPage() throws Exception {
this.mockMvc.perform(get(RANDOM_URL))
.andDo(print());
}
print() returns:
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {X-Application-Context=[application:integration:-1]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
So I cant created something like this:
.andExpect(forwardedUrl("error-page"));
because it fails, but on manual tests error-page is returned.
Testing of a custom ErrorController with MockMvc is unfortunately not supported.
For a detailed explanation, see the official recommendation from the Spring Boot team (source).
To be sure that any error handling is working fully, it's necessary to
involve the servlet container in that testing as it's responsible for
error page registration etc. Even if MockMvc itself or a Boot
enhancement to MockMvc allowed forwarding to an error page, you'd be
testing the testing infrastructure not the real-world scenario that
you're actually interested in.
Our recommendation for tests that want to be sure that error handling
is working correctly, is to use an embedded container and test with
WebTestClient, RestAssured, or TestRestTemplate.
My suggestion is to use #ControllerAdvice
In this way you can work around the problem and you can continue to use MockMvc with the big advantage that you are not required to have a running server.
Of course to test explicitly the error page management you need a running server. My suggestion is mainly for those who implemented ErrorController but still want to use MockMvc for unit testing.
#ControllerAdvice
public class MyControllerAdvice {
#ExceptionHandler(FileSizeLimitExceededException.class)
public ResponseEntity<Throwable> handleFileException(HttpServletRequest request, FileSizeLimitExceededException ex) {
return new ResponseEntity<>(ex, HttpStatus.PAYLOAD_TOO_LARGE);
}
#ExceptionHandler(Throwable.class)
public ResponseEntity<Throwable> handleUnexpected(HttpServletRequest request, Throwable throwable) {
return new ResponseEntity<>(throwable, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

Spring Mvc REST api test | jQuery serialized form data-binding

First of all, i'm not a pro with tests, actually i'm learning to use them, and i'm finding myself in a lot of trouble trying to test Spring Controllers with the Spring Test framework, so i did the test after the production code, because i didn't know exactly how build the test.
The project is a Spring Boot (1.2.3) with Web, Thymeleaf, Security, MongoDB and Actuator modules, and using the platform-bom (1.1.2) for version management.
The functionality is easy, while the user fills a form, ajax requests using jQuery are sent to the server to verify the last field the user filled, then the server performs validation, and returns a JSON response.
Client side validation is not an option because some information has to be queried to a database to perform the validation (like if a username is already in use or not), so it needs to be done server side.
Also all the validation is performed with Hibernate Validator and custom annotations, both field and class annotations, since we use 1 entry point to perform the interactive form validation, the entire form is send in each request.
Here is the method signature (and first validations) in a #RestController :
#RequestMapping(value = "/some-url", method = RequestMethod.POST)
public ResponseEntity<ValidationResponse> validateFormField(
#Valid #ModelAttribute UserRegistrationForm form, BindingResult result) {
if (form == null || form.getSomeValue() == null) {
return new ResponseEntity<ValidationResponse>(HttpStatus.BAD_REQUEST);
}
// more input validation and actions
}
Now the call code, using jQuery:
$.ajax({
url: '/some-url',
type: 'post',
data: $(selector).serialize(),
dataType: 'json',
...
});
Now, the unit test code i'm writting to automatic test this is:
#ActiveProfiles("testing")
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {
Application.class, WebConfiguration.class,
MongoConfiguration.class, SecurityConfiguration.class
})
#WebAppConfiguration
public class RegistrationInteractiveValidationRestControllerTest {
#Resource
private FilterChainProxy springSecurityFilterChain;
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
mockMvc = webAppContextSetup(wac)
.addFilter(springSecurityFilterChain)
.build();
}
#Test
public void withValidInput_returnStatusOK() throws Exception {
// test init
MockHttpServletRequestBuilder ajaxRequest = post("/some-url")
.content( "username=Bobby&email=& ...more fields... " )
.secure( true ) .with( csrf().asHeader() );
// test action
ResultActions performRequest = mockMvc.perform(ajaxRequest);
// test verification
performRequest.andExpect( status().isOk() );
}
#Test
public void withInvalidInput_returnStatusBadRequest() throws Exception {
// test init
MockHttpServletRequestBuilder ajaxRequest = post("/some-url")
.content( "{ 'im' : 'a bad content request' }" )
.secure( true ) .with( csrf().asHeader() );
// test action
ResultActions performRequest = mockMvc.perform(ajaxRequest);
// test verification
performRequest.andExpect(status().isBadRequest());
}
}
The second test goes alright, status code is 400 as expected, but in the first test, it fails because it also returns a 400.
I did some test debugging and the form object itself is not null, but all its fields are null.
But if i deploy the app in a server, and do the test manually, it works just fine, ajax calls get responses with valid JSON and HTTP 200 status codes.
I also did some debugging of the app deployed in a server and the databinding works just fine.
My thoughts are that i'm missing something building the request in the test, so what i've tried is to verify in the browser the request headers and form data when the app is deployed on a server, and added those to the requests i'm building in the tests, all of them, without any luck at all.
I've researched also the Spring Framework, Spring Boot, Spring security and Spring Test reference documentation, and I didn't find anything that could lead me to the right answer.

Resources