如何通过测试类将json文件传递给API以使用@Requestpart测试API

时间:2019-04-17 05:19:55

标签: java spring junit rest-assured

用一个参数@Requestpart为API编写测试用例,我尝试发送文件,multipartfile对象来调用该方法,但是没有用

这是API

    @RequestMapping(value = "messages", method = RequestMethod.POST)
        public @ResponseBody
        MessageResponse sendMessage(@RequestHeader String authCode,
                                    @RequestPart SendMessageRequest sendMessageRequest,
                                    @RequestPart List<MultipartFile> mediaFiles) {
            MessageResponse messageResponse = new MessageResponse();
            List<String> validationErrors = new ArrayList<>();
            try {
                if (StringUtils.isBlank(authCode) || authCode.length() < 30) {

    **This is my Test Class**

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:testApplicationContext.xml"})
@WebAppConfiguration
@Transactional
public class MessageControllerTest {
    @Autowired
    private WebApplicationContext context;

    private final File jsonpath = new File("src/test/resources/testFiles");

    @Before
    public void setUp() throws Exception {
        RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(context)
                .apply(springSecurity()).build());

    }

 @Test
    public void sendMessage() throws Exception {
        File f = new File("src\\test\\resources\\testFiles\\New.json");
        byte[] json = "{\"text\":\"Hai, how are you?\",\"from\":\"+15102106111\",\"to\":\"+15109721012\",\"callbackURL\":\"\"}".getBytes(StandardCharsets.UTF_8);
        InputStream inputstream = new FileInputStream("src\\test\\resources\\testFiles\\New.json");
        MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", inputstream);
       // MockMultipartFile mockMultipartFile = new MockMultipartFile("sendMessageRequest",inputstream);
        given().
                header("authCode", "ref545654r6tf5rty5rtf5rt5rt56812").
                multiPart("sendMessageRequest",jsonPart).
                when().
                post("/starbucks/api/v1/messages.json").
                then().
                statusCode(HttpServletResponse.SC_OK).
                contentType(ContentType.JSON).
                body("status", equalTo("success")).
                body("sessionExpired=", equalTo("false"));

    }
}

我期望调用该方法,但是我得到的是以下异常

“ com.fasterxml.jackson.databind.JsonMappingException:未找到类java.io.ByteArrayInputStream的序列化器,也未找到创建BeanSerializer的属性(此处的帐篷代码,请避免异常,请禁用SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过参考链:org。 springframework.mock.web.MockMultipartFile [“ inputStream”])“

0 个答案:

没有答案