Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possible bug on Spring MVC Test about retrieving XML [SPR-13684] #18259

Closed
spring-issuemaster opened this issue Nov 13, 2015 · 2 comments
Closed

Possible bug on Spring MVC Test about retrieving XML [SPR-13684] #18259

spring-issuemaster opened this issue Nov 13, 2015 · 2 comments
Assignees

Comments

@spring-issuemaster
Copy link
Collaborator

@spring-issuemaster spring-issuemaster commented Nov 13, 2015

Manuel Jordan opened SPR-13684 and commented

Hello

I have the following configuration class:

@Configuration
public class HttpMessageConverterConfig {

	@Bean
    public MarshallingHttpMessageConverter marshallingMessageConverter() {
        MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter();
        converter.setMarshaller(jaxbMarshaller());
        converter.setUnmarshaller(jaxbMarshaller());
        return converter;
    }
	
    @Bean
    public Jaxb2Marshaller jaxbMarshaller() {
        Jaxb2Marshaller jaxbMarshaller = new Jaxb2Marshaller();
        jaxbMarshaller.setClassesToBeBound(PersonaXml.class, 
                                                                      PersonaCollection.class, 
                                                                      GenericCollection.class,
                                                                      PersonaHibrid.class);
           
        Map<String, Object> props = new HashMap<>();
        props.put(Marshaller.JAXB_ENCODING,"UTF-8");
        props.put(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.setMarshallerProperties(props);
        
        return jaxbMarshaller;
    }
	
    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
    	MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    	converter.setPrettyPrint(true);		
    	return converter;
    }
    
}

Furthermore, I have these two @Controllers methods

	@RequestMapping(value=PersonaUrlHelperComplement.FINDONE)
	public @ResponseBody PersonaXml findOneRequestParamById(@RequestParam String id){
		logger.info("findOneRequestParamById called...");
		return personas.get(id);
	}

	// With Extension .xml
	
	@RequestMapping(value=PersonaUrlXmlHelper.FINDONE_XML_EXTENSION)
	public @ResponseBody PersonaXml findOneRequestParamByIdWithExtension(@RequestParam String id){
		logger.info("findOneRequestParamByIdWithExtension called...");
		return personas.get(id);
	}	

If I execute any of the following URLs in a Web Browser:

I can see the following output:

<persona>
     <id>100</id>
     <nombre>Jesús Você</nombre>
     <apellido>Mão Nuñez</apellido>
     <fecha>2015-11-13T11:40:59.020-05:00</fecha>
</persona>

Do realize about the weird characters ú ê ã ñ appears fine.

I am fine until here. About Testing

I have the two following @Test methods:

 @Before
public void setUp() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
       @Test
                                                                 public void findOneRequestParamByIdTest() throws Exception {	
      logger.info("Testing: {}", name.getMethodName());
      mockMvc.perform(get(PersonaUrlXmlHelperComplement.ROOT_URL_XML + 
                                           PersonaUrlHelperComplement.FINDONE +
                                           ID_PARAM, ID))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_XML));
 }
  @Test
 public void findOneRequestParamByIdWithExtensionTest() throws Exception {
      logger.info("Testing: {}", name.getMethodName());
      mockMvc.perform(get(PersonaUrlXmlHelperComplement.ROOT_URL_XML + 
                                  PersonaUrlXmlHelper.FINDONE_XML_EXTENSION +
                                  ID_PARAM, ID))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_XML));
 }

Through

  1. Gradle test task
  2. or even doing in the Test Class right click and selecting Run As -> JUnit Test

I can see always the following thanks to the .andDo(print())

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/xml]}
     Content type = application/xml
             Body = <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persona>
    <id>100</id>
    <nombre>Jesús Você</nombre>
    <apellido>Mão Nuñez</apellido>
    <fecha>2015-11-13T11:38:17.033-05:00</fecha>
</persona>

    Forwarded URL = null
   Redirected URL = null
          Cookies = []

See that the weird characters fail.

I can see:

Headers = {Content-Type=[application/xml]}

where does not contain nothing about UTF-8.

I don't know if it is related with Add MediaType.APPLICATION_JSON_UTF8 and improve documentation, of course for XML.

What is missing or wrong?


Affects: 4.2 GA

@spring-issuemaster
Copy link
Collaborator Author

@spring-issuemaster spring-issuemaster commented Nov 14, 2015

Manuel Jordan commented

Hello

I can confirm it is a kind bug only when the data is printed, because I have the following:

mockMvc.perform(get(url, ID))
          .andDo(print())
          .andExpect(status().isOk())
                                                                                                                                                                                                                      .andExpect(content().contentType(MediaType.APPLICATION_XML))			
          .andExpect(xpath("persona").exists())
          .andExpect(xpath("persona").nodeCount(1))
          .andExpect(xpath("persona/id").exists())
          .andExpect(xpath("persona/id").string("100"))
          .andExpect(xpath("persona/nombre").exists())
          .andExpect(xpath("persona/nombre").string("Jesús Você"))
          .andExpect(xpath("persona/apellido").exists())
          .andExpect(xpath("persona/apellido").string("Mão Nuñez"))
          .andExpect(xpath("persona/fecha").exists())
                    ;

Observe that I am doing a comparison with the data with the weird characters and the test method passes fine. But however the data through print() shows the weird characters in the wrong way.

@spring-issuemaster
Copy link
Collaborator Author

@spring-issuemaster spring-issuemaster commented Nov 17, 2015

Rossen Stoyanchev commented

The PrintingResultHandler that's behind .andDo(print()) is a simple mechanism to print the response to the console for debugging reasons. Internally it relies on getContentAsString() of MockHttpServletResponse which checks the characterEncoding of the response and if that's not present uses the platform default encoding. In this case there is no encoding specified so this is to be expected.

By the way in your tests you're also relying implicitly on the default platform encoding. Those expectations might work okay on your computer and fail on another (e.g. CI server) if the default platform encoding is different. Instead you should use native2ascii converter and embed escaped sequences "Jes\u00fas Voc\u00ea".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants
You can’t perform that action at this time.