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

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());
}

Related

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 to check Bad request for #Min on request param in spring controller?

I am pretty new to spring controller. I am trying to write unit test for invalid parameter. I have an api that has #RequestParam("id") #Min(1) long id and in my unit test, I pass in "-1". Here is my test:
#Test
public void searchWithInvalidIbId() throws Exception {
mockMvc.perform(get(BASE_URL)
.param(COLUMN_IB_ID, INVALID_IB_ID_VALUE) // = "-1"
.param(COLUMN_TIME_RANGE, TIME_RANGE_VALUE)
.param(COLUMN_TIME_ZONE, TIME_ZONE_VALUE)
.accept(PowerShareMediaType.PSH_DISPATCH_REPORTER_V1_JSON)
.contentType(PowerShareMediaType.PSH_DISPATCH_REPORTER_V1_JSON))
.andExpect(status().isBadRequest());
}
When I run this, I get
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException: search.arg2: must be greater than or equal to 1
It makes sense, but I am not sure how to test this is BadRequest. I tried #Test(expected = NestedServletException.class), and it passed, but I don't think it is checking what I want to check. What is the right approach to check this?
You can have your custom exception handler annotated with #ControllerAdvice and handle ConstraintViolationException in that class. You can throw your custom exception with additional details if you wish.
Here is an example approach:
#ControllerAdvice
public class MyCustomExceptionHandler {
#ResponseBody
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ExceptionHandler(ConstraintViolationException.class)
ApiError constraintViolationException(ConstraintViolationException e) {
return BAD_REQUEST.apply(e.getBindingResult());
}
}
Here ApiError is a custom class to represent your error response, it can be anything else you want. You can add timestamp, http status, your error message etc.

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 mockMVC testing method GET

i created post method in mockMVC (in spring boot project)
This is my method testing
This is my method testing
#Test
public void createAccount() throws Exception {
AccountDTO accountDTO = new AccountDTO("SAVINGS", "SAVINGS");
when(addaccountService.findByName("SAVING")).thenReturn(Optional.empty());
when(addaccountService.createAccount(any())).thenReturn(createdAccountDTO);
CreatedAccountDTO createdAccountDTO = new CreatedAccountDTO("a#wp.pl", "SAVINGS", "1234rds", uuid);
mockMvc.perform(
post("/account").contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(AccountNewDTO)))
.andExpect(status().isCreated())
.andExpect(header().string("location", containsString("/account/"+uuid.toString())));
System.out.println("aaa");
}
I want to write GET method.
how to write a get method in mock mvc? how to verify whether what I threw was returned?
You can try the below for Mockmvc perform get and post methods
For get method
#Autowired
private MuffinRepository muffinRepository;
#Test
public void testgetMethod throws Exception(){
Muffin muffin = new Muffin("Butterscotch");
muffin.setId(1L);
BddMockito.given(muffinRepository.findOne(1L)).
willReturn(muffin);
mockMvc.perform(MockMvcRequestBuilders.
get("/muffins/1")).
andExpect(MockMvcResutMatchers.status().isOk()).
andExpect(MockMvcResutMatchers.content().string("{\"id\":1, "flavor":"Butterscotch"}"));
}
//Test to do post operation
#Test
public void testgetMethod throws Exception(){
Muffin muffin = new Muffin("Butterscotch");
muffin.setId(1L);
BddMockito.given(muffinRepository.findOne(1L)).
willReturn(muffin);
mockMvc.perform(MockMvcRequestBuilders.
post("/muffins")
.content(convertObjectToJsonString(muffin))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResutMatchers.status().isCreated())
.andExpect(MockMvcResutMatchers.content().json(convertObjectToJsonString(muffin)));
}
If the response is empty then make sure to override equals() and hashCode() method on the Entity your repository is working with
//Converts Object to Json String
private String convertObjectToJsonString(Muffin muffin) throws JsonProcessingException{
ObjectWriter writer = new ObjectWriter().writer().withDefaultPrettyPrinter();
return writer.writeValueAsString(muffin);
}
You can use the static get method of the class MockMvcRequestBuilders, see: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.html#get-java.lang.String-java.lang.Object...-
Example:
mockMvc.perform(get("/account")).andExpect(...);
If you throw an exception within your controller method it will typically trigger execution of an exception handler which transforms the exception into a HTTP error response. By default, you could check if the status of the response was 500. If you have implemented your own exception handler you may want to check the response body as well to verify if it contains the expected error data.

How to check returntype in Spring Unittest using MockMVC?

The Spring method I wanna test
#RequestMapping(value="/files", method=RequestMethod.GET)
#ResponseBody
public List<FileListRequest> get() {
return getMainController().getAllFiles();
}
I want to be assured all calls to /files are responded with an List[FileListRequest]. How?
This is the method in which the test is supposed to be.
#Test
public void testGetAll() throws Exception {
this.mockMvc.perform(get("/files").accept("application/json"))
.andExpect(status().isOk())
.andExpect(content().contentType(SOMETHING);
}
Can I simply replace the SOMETHING or am I totally wrong?
Can I run assert methods on the object returned by perform()?
Edit:
MvcResult result = this.mockMvc.perform(get("/files").accept("application/json"))
.andExpect(status().isOk())
.andReturn();
String content = result.getResponse().getContentAsString();
// Convert json String to Respective object by using Gson or Jackson
ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory=objectMapper.getTypeFactory();
List<SomeClass> someClassList =mapper.readValue(content , typeFactory.constructCollectionType(List.class, SomeClass.class));
//Assert here with your list
You could use Json Path to check if specific data exist in your response
a code snipper from by old project
mockMvc.perform(get("/rest/blogs")) .contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.blogs[*].title",
hasItems(endsWith("Title A"), endsWith("Title B"))))
.andExpect(status().isOk());
You cannot use contentType to check the class of instances. The Content-Type is to determine the format of text sent/returned in a HTTP(S) request/response, and has nothing to do with programmatic type-check. It only regulates that the request/response is in json/text-plain/xml, etc.
To check the type of the objects returned in the response, let's assume that the response is in format JSON(built-in Jackson in Spring boot will do the (un)marshalling), and we just use org.hamcrest.Matchers.instanceOf(Class<?> type) to check the class of first item in the list, with jsonPath.
A working snippet:
import static org.hamcrest.Matchers.instanceOf;
...
#Test
public void testBinInfoControllerInsertBIN() throws Exception {
when(this.repository.save(mockBinInfo)).thenReturn(mockBinInfo);
this.mockMvc.perform(post("/insert")
.content("{\"id\":\"42\", \"bin\":\"touhou\", \"json_full\":\"{is_json:true}\", \"createAt\":\"18/08/2018\"}")
.accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
)
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isCreated())
.andExpect(jsonPath("$[0]", instanceOf(BinInfo.class)))
.andExpect(jsonPath("$[0].bin", is("touhou")));
}
If you want to check every item in the list... maybe it is redundant? I haven't seen code examining each and every item in the list because you have to iterate. There is way, of course.

Resources