I have a Spring Boot @RestController which hast an upload endpiont that gets an object as input.

 public ResponseEntity<Void> upload(String productId, Boolean dryrun, ProductConfig product) 

This endpoint receives an xml file with a ProductConfig in it. I have some Jackson annotations for renaming xml elements and configuration to use unwrapped lists by default on the Jackson2ObjectMapperBuilder and it works fine.

So my problem is now that I need this ObjectMapper inside one of my tests to parse one of those xml files from the resources. I tried two different things:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TestIntegrationTest {

    @Autowired ObjectMapper mapper;

    @Test
    public void test() throws Exception{

        Resource res = new ClassPathResource("SimpleConfig.xml");
        ProductConfig conf = mapper.readValue(res.getFile(), ProductConfig.class);
    }
}

and

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TestIntegrationTest {

    @Test
    public void test() throws Exception{
        XmlMapper mapper = new XmlMapper();
        mapper.setDefaultUseWrapper(false);

        Resource res = new ClassPathResource("SimpleConfig.xml");
        ProductConfig conf = mapper.readValue(res.getFile(), ProductConfig.class);
    }
}

The first one is the one I would have expected to work but it crashes with a parse exception on the '<'character, which seems that it wants to parse json and not xml, but in the @RestController it gets parsed perfectly,... or is ObjectMapper just not the class that does the parsing for the @RestController?

In the second example it fails to parse some nested classes namely ProductConfig can have a list of Units, which is an unrwapped list of <unit> child elements. The respective part of the model is:

  @JsonProperty("units")
  @JacksonXmlProperty(localName = "unit")
  @Valid
  private List<Unit> units = null;

This works when I just upload the xml to the rest endpoint but doesn't work when I invoke the XmlMapper manually.

The xml looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<product name="foobar">
    <unit  target="config">
        <property name="prop1" value="foo"/>

        <unit target="sub1">
            <property name="prop1" value="foo"/>
            <property name="prop2" value="bar"/>
            <property name="prop3" value="blah"/>
        </unit>
        <unit target="sub2">
           ....
        </unit>
        ...
    </unit>
</product>

Any ideas on how to reproduce the parsing the @RestController does for tests?

0 Answers