使用MockMultipartFile和HttpMessageConversionException进行的接受测试

时间:2019-05-09 08:44:20

标签: spring-boot junit

我在springboot中尝试了MockMultipartFile类的AcceptanceTest,并且发生了HttpMessageConversionException

并且我看到许多代码可用于File Object,但是正如您所见,我的dto包含MultipartFile。

您知道我为什么不起作用吗?以及如何解决?

这是杰克逊转换错误,所以我检查了所有的get〜方法和 我尝试制作CustomMultipartFile并覆盖getInputStream方法并附加@JsonIgnore 但这会导致另一个错误,并且不起作用


org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class java.io.ByteArrayInputStream]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.mock.web.MockMultipartFile["inputStream"])

    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:293)
    at org.springframework.http.converter.AbstractGenericHttpMessageConverter.writeInternal(AbstractGenericHttpMessageConverter.java:112)
    at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:227)
    at org.springframework.http.converter.FormHttpMessageConverter.writePart(FormHttpMessageConverter.java:417)
    at org.springframework.http.converter.FormHttpMessageConverter.writeParts(FormHttpMessageConverter.java:393)
    at org.springframework.http.converter.FormHttpMessageConverter.writeMultipart(FormHttpMessageConverter.java:373)
    at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:277)
    at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:95)
    at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:948)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:733)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:579)
    at org.springframework.boot.test.web.client.TestRestTemplate.exchange(TestRestTemplate.java:774)
    at com.mappractice.demo.acceptanceTest.AcceptanceTest.sendFile(AcceptanceTest.java:51)
    at com.mappractice.demo.acceptanceTest.ImageAcceptanceTest.이미지_생성_API_성공(ImageAcceptanceTest.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.mock.web.MockMultipartFile["inputStream"])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77)
    at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1191)
    at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:313)
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:71)
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:33)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
    at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1396)
    at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:913)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:287)
    ... 45 more

测试代码


public class ImageAcceptanceTest extends AcceptanceTest {
    private static final String API_IMAGE_URI = "/api/image";

    private static MockMultipartFile content;
    private static Image image;
    private static PositionedImageDTO positionedImageDTO;

    @BeforeClass
    public static void init() {
        content = new MockMultipartFile("file",
                "ded.png",
                "image/png",
                "datdedadsdwdssdwa".getBytes()
        );
        image = new Image(1L, "테스트 이미지", "12kl312nlk3".getBytes(), new Location("12.1234567", "12.1234566"));
        positionedImageDTO = new PositionedImageDTO("테스트 이미지", content, "12.1234567", "12.1234566");
    }

    @Test
    public void image_create_API_success() {
        MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
        parameters.add("fileName", "테스트 이미지");
        parameters.add("file", content);
        parameters.add("xIndex", "123");
        parameters.add("yIndex", "454");

        ResponseEntity<Image> responseEntity = sendFile(API_IMAGE_URI, parameters, Image.class);
        assertThat(responseEntity.getBody().getName()).isEqualTo("테스트 이미지");
    }

...

控制器代码


@RestController
@RequestMapping("/api/image")
public class ApiImageController {

    ...

    @PostMapping("")
    public ResponseEntity<Image> create(@ModelAttribute PositionedImageDTO positionedImageDTO){
        Image image = imageService.create(positionedImageDTO);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setLocation(URI.create("/api/image/"+image.getId()));
        return new ResponseEntity<>(image, headers, HttpStatus.CREATED);
    }

    ...

}

DTO代码


@Getter
@Setter
@NoArgsConstructor
@ToString
public class PositionedImageDTO {

    @NotEmpty
    private String fileName;

    @NotEmpty
    private MultipartFile file;

    @NotNull
    private String xIndex;

    @NotNull
    private String yIndex;

    public PositionedImageDTO(String fileName, MultipartFile file, String xIndex, String yIndex) {
        this.fileName = fileName;
        this.file = file;
        this.xIndex = xIndex;
        this.yIndex = yIndex;
    }

    public String getExtentionFormat() {
        return "." + file.getContentType().split("/")[1];
    }
}

0 个答案:

没有答案