I am writing a Test case in Spring boot 1.5.6 Release as shown below:
#Test
public void auditTrailSenderTest() throws Exception {
String queryParameters = "auditActionId=#Create&objectTypeId=#AccBalance";
mockMvc.perform(post("/api/v10/event?"+queryParameters))
.andExpect(status().isOk());
}
The problem is that due to presence of hash in #Create and #AccBalance, the test case fails with status of 400. If i replace # with %23, then it is passed as '%23' without being converted to hash ('#') in Rest Api.
Is there any way to escape this number sign ('#') in query string parameters?
Related
How to generate saml response token manually, like encoded string ? I have test like this
#Test
public void testSuccessCase() throws Exception {
WebSSOProfileConsumerImpl customWebSSOProfileConsumer = (WebSSOProfileConsumerImpl) webSSOProfileConsumer;
customWebSSOProfileConsumer.setResponseSkew(1111111111);
String samlToken = "PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiIElEPSJfYzVlNmZjNmNkYmRmYTRlZTUwNmQiICBWZXJzaW9uPSIyLjAiIElzc3VlSW5zdGFudD0iMjAyMi0wOS0yOFQxMzo1MTo1Ny43NThaIiAgRGVzdGluYXRpb249Imh0dHA6Ly9sb2NhbGhvc3Qvc2FtbC9TU08iPjxzYW1sOklzc3VlciB4bWxuczpzYW1sPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIj51cm46ZGV2LWc5MS1hc2s1LnVzLmF1dGgwLmNvbTwvc2FtbDpJc3N1ZXI+PHNhbWxwOlN0YXR1cz48c2FtbHA6U3RhdHVzQ29kZSBWYWx1ZT0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOnN0YXR1czpTdWNjZXNzIi8+PC9zYW1scDpTdGF0dXM+PHNhbWw6QXNzZXJ0aW9uIHhtbG5zOnNhbWw9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDphc3NlcnRpb24iIFZlcnNpb249IjIuMCIgSUQ9Il96WjBkRDF0c0VYcmgyZExMUjFpNE0xdGo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NDg6MjUgR01UKzAwMDAgKENvb3JkaW5hdGVkIFVuaXZlcnNhbCBUaW1lKTwvc2FtbDpBdHRyaWJ1dGVWYWx1ZT48L3NhbWw6QXR0cmlidXRlPjxzYW1sOkF0dHJpYnV0ZSBOYW1lPSJodHRwOi8vc2NoZW1hcy5hdXRoMC5jb20vaWRlbnRpZmllciIgTmFtZUZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmF0dHJuYW1lLWZvcm1hdDp1cmkiPjxzYW1sOkF0dHJpYnV0ZVZhbHVlIHhzaTp0eXBlPSJ4czpzdHJpbmciPmF1dGgwfDYzMjQ0NmRhZDhkOTBiMjQ3NDgxNDg3NDwvc2FtbDpBdHRyaWJ1dGVWYWx1ZT48L3NhbWw6QXR0cmlidXRlPjwvc2FtbDpBdHRyaWJ1dGVTdGF0ZW1lbnQ+PC9zYW1sOkFzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==";
ResultActions perform = this.mockMvc.perform(post("/saml/SSO")
.param("SAMLResponse", samlToken)
.contentType(MediaType.APPLICATION_FORM_URLENCODED));
MvcResult mvcResult = perform.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String redirectedUrl = response.getRedirectedUrl();
ResultActions resultActions = perform.andDo(print());
assertThat(redirectedUrl, containsString(authServiceUrl));
}
where I used samlToken which configured for me resource auth0 debug saml opportunity and I set setResponseSkew for use this tken during 111111111 seconds, but this is hard hack and looks like not right solution, so how I can generate this token manually in code like this create some object of clas and then execute some encode function for generate samlToken and use it?
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());
}
I would like to pass an input file to MockMVC perform statement. Please find the code snippet below:
#Test
public void test() throws Exception {
this.mockMvc.perform(post("/tax_rates/v1/quotations")
.contentType(MediaType.APPLICATION_JSON_UTF8).pathInfo("/src/main/resources/input.json"))
.andExpect((ResultMatcher) status().is2xxSuccessful());
}
When I tried using pathInfo variable I get the error as below:
HttpMessageNotReadableException: Required request body is missing:
which i guess it means payload is not getting passed?
Any suggestions would help me.
Regards,
Sunil
we can pass json input as content :
ObjectMapper mapper=new ObjectMapper();
String jsonString=mapperwriteValueAsString(mapper.readValue(new File("path/to/file",Object.class));
this.mockMvc.perform(post("/tax_rates/v1/quotations")
.contentType(MediaType.APPLICATION_JSON_UTF8).content(jsonString))
.andExpect(status().is2xxSuccessful());
If you want to pass MultipartFile as input. Here is the link:
Using Spring MVC Test to unit test multipart POST request
I am working with Spring Framework version 4.3.6.
It works with RestTemplate and thus offers support for XML and JSON
Reminder: about HTTP methods, for POST and PUT has sense mandatorily define the Content-Type header. It either for XML or JSON.
I have a situation for RequestEntity<Object> about testing:
I have the following creation for POST
RequestEntity<Object> requestEntity =
RequestEntity.post(uri).contentType(MediaType.APPLICATION_XML)
.header("Accept-Language", locale.toString())
.body(entity);
Until here it works fine when none exception is thrown by the server. It means, the entity is saved or persisted in the database without problem.
I have a problem when in other testing scenario the entity already exists in the database. I have a #ControllerAdvice that works through #ExceptionHandler. The server side works how is expected. It catchs the exception and generates an error message but...
...the problem only happens with XML, I get the following error message (the #Test method fails of course)
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '{' (code 123) in prolog; expected '<'
at [row,col {unknown-source}]: [1,1]; nested exception is java.io.IOException: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '{' (code 123) in prolog; expected '<'
at [row,col {unknown-source}]: [1,1]
I did realize the unique way to avoid that error message is through the following edition:
RequestEntity<Object> requestEntity =
RequestEntity.post(uri).contentType(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_XML)//<---- new
.header("Accept-Language", locale.toString())
.body(entity);
I am confused why it works, it because for POST is not mandatory define the Accept header. Even when in the server side I can define for the ResponseEntity<Object> (response) the Content-Type and Accept headers to XML value, the #Test fails. The unique way to solve this is adding for the RequestEntity<Object> (request) the .accept(MediaType.APPLICATION_XML) part.
Here the other problem is that we must assume other Java developers using RestTemplate are going to create the RequestEntity<Object> object with just defining the Content-Type and without defining the Accept header.
Note: it fails even when the RestTemplate uses the setErrorHandler method
Again, it only happens with XML, for JSON I have the following:
RequestEntity<Object> requestEntity =
RequestEntity.post(uri).contentType(MediaType.APPLICATION_JSON_UTF8)
.header("Accept-Language", locale.toString())
.body(entity);
and always works for valid and invalid (an entity already persisted) scenarios.
What is the best approach to around this situation?
Alpha
Even If I do the following edition how was suggested:
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true)
.favorParameter(false)
.ignoreAcceptHeader(false)
//.defaultContentType(new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8))
.defaultContentType(new MediaType(MediaType.APPLICATION_XML, StandardCharsets.UTF_8))
.mediaType("html", MediaType.TEXT_HTML)
.mediaType("xml", new MediaType(MediaType.APPLICATION_XML, StandardCharsets.UTF_8))
.mediaType("json", MediaType.APPLICATION_JSON_UTF8);
}
I get the same situation
About XML, I don't use JAXB2 because it does not support Generic Collections, thus I use Jackson jackson-dataformat-xml
Important I only have this situation when is used RequestEntity<Object> with RestTemplate, for other testings working around
ResultActions resultActions =
mockMvc.perform(post(uri).contentType(MediaType.APPLICATION_XML)
.header("Accept-Language", locale.toString())
.content(entity)).andDo(print());
Observe, there is no a .accept(MediaType.APPLICATION_XML) sentence.
All work fine.
Application/json is probably configured as the default media type in your services application somewhere. That is why unless you specify the Accept header to be application/xml, you are getting json response.
If you want to make application/xml your default response media type, you will need to configure the ContentNegotiationManagerFactoryBean (Maybe you are already doing this but for application/json). Something like this:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
/**
* Setup a simple strategy: use all the defaults and return XML by default when not sure.
*/
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_XML);
}
}
You can find this in spring documentation here.
The other thing you need to look at is the entity you are using in error scenarios. If it is properly annotated with Jaxb annotations (#XmlRootElement)
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.