繁体   English   中英

春季启动测试:测试响应抛出“找不到可接受的表示形式”,应用正常运行

[英]Spring Boot Test: Test Response throws “Could not find acceptable representation” , App works correctly

我正在使用Spring Boot创建一个应用程序。 当我运行我的应用程序并测试服务时,我得到了正确的信息。

服务正在运行的图片

但是,当我运行如下测试时:

public class CatalogControllerTet {
    private MockMvc mvc;
    @Autowired
    private WebApplicationContext context;
    @Autowired
    private CatalogRepository catalogRepository;

    @Before
    public void setUp() throws Exception {
        this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
    }

    @Test
    public void getHello() throws Exception {

        MvcResult r = mvc.perform(MockMvcRequestBuilders
                .get("/catalogs")
                .accept(MediaType.APPLICATION_JSON)).andReturn();
        String content = r.getResponse().getContentAsString();
        int i = 100;
    }
}

当我在测试中设置断点时,我看到了。 我注意到的一件事是,在“ supportedMediaTypes”列表中没有提及JSON的任何内容。

我也见过其他一些类似的问题,但是它们可以追溯到响应对象,没有任何获取方法/设置方法或与Jackson库有关。 服务启动并正确运行的事实意味着不是这些问题。

在此处输入图片说明

在此方面的任何帮助将不胜感激。

我在集成测试文件上将@DataJpaTest列为注释。 我永远不会知道为什么会显示为此错误,但确实如此。

作品:

@RunWith(SpringRunner.class)
@SpringBootTest
public class CatalogControllerITTest {
...

不起作用:

@RunWith(SpringRunner.class)
@SpringBootTest
@DataJpaTest
public class CatalogControllerITTest {
...

非常非常令人惊讶和阴险的行为,因为从不会怀疑注释会对Servlet如何处理响应产生影响。

您的控制器可能类似于以下内容。

package hello;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class HelloController {

    @RequestMapping(value="/catalogs", produces={"application/json"})
    @ResponseBody
    public String catalogs() {
        return "{\"catalogslist\":[], \"tupleslist\":[]}";
    }

}

然后以下测试成功。

package hello;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class HelloControllerTest {

    private MockMvc mvc;

    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void getHello() throws Exception {

        MvcResult r = mvc.perform(MockMvcRequestBuilders
                .get("/")
                .accept(MediaType.APPLICATION_JSON)).andReturn();


        mvc.perform(MockMvcRequestBuilders.get("/catalogs").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("{\"catalogslist\":[], \"tupleslist\":[]}")));
    }
}

测试成功。

在此处输入图片说明

如果您需要样板,欢迎使用我的样板进行新的弹簧靴项目。 您只需克隆并运行它:

git clone https://github.com/montao/spring-boot-loaded.git
Cloning into 'spring-boot-loaded'...
remote: Counting objects: 25, done.
remote: Total 25 (delta 0), reused 0 (delta 0), pack-reused 25
Unpacking objects: 100% (25/25), done.
Checking connectivity... done.
dac@dac-Latitude-E7450 ~/spring-boot-loaded> ls
spring-boot-loaded/
dac@dac-Latitude-E7450 ~/spring-boot-loaded> cd spring-boot-loaded/
dac@dac-Latitude-E7450 ~/s/spring-boot-loaded> gradle bootRun
Starting a Gradle Daemon (subsequent builds will be faster)
:compileJava
:processResources UP-TO-DATE
:classes
:findMainClass
:bootRun

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.6.RELEASE)

一个更高级的示例实际上是从Java对象创建json,然后对其进行测试。

调节器

package hello;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.w3c.dom.Entity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
class HelloController {
    private class User {

        private String name;

        public int getAge() {
            return age;
        }

        void setAge(int age) {
            this.age = age;
        }

        private int age;

        public List<String> getMessages() {
            return messages;
        }

        void setMessages(List<String> messages) {
            this.messages = messages;
        }

        private List<String> messages;

        public String getName() {
            return name;
        }

        void setName(String name) {
            this.name = name;
        }

        //getters and setters
    }

    private User createDummyUser() {

        User user = new User();

        user.setName("Mallory");
        user.setAge(33);

        List<String> msg = new ArrayList<>();
        msg.add("hello jackson 1");
        msg.add("hello jackson 2");
        msg.add("hello jackson 3");

        user.setMessages(msg);

        return user;

    }

    @RequestMapping(value = "/catalogs2", produces = {"application/json"})
    @ResponseBody
    public String catalogs() {
        String jsonInString = "";
        String json = "";
        User user = createDummyUser();
        ObjectMapper mapper = new ObjectMapper();
        try {
            //Convert object to JSON string and save into file directly
            mapper.writeValue(new File("user.json"), user);

            //Convert object to JSON string
            jsonInString = mapper.writeValueAsString(user);
            System.out.println(jsonInString);

            //Convert object to JSON string and pretty print
            jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            json = ow.writeValueAsString(jsonInString);

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

}

测试

package hello;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class HelloControllerTest {
    private class User {

        private String name;

        public int getAge() {
            return age;
        }

        void setAge(int age) {
            this.age = age;
        }

        private int age;

        public List<String> getMessages() {
            return messages;
        }

        void setMessages(List<String> messages) {
            this.messages = messages;
        }

        private List<String> messages;

        public String getName() {
            return name;
        }

        void setName(String name) {
            this.name = name;
        }

        //getters and setters
    }

    private User createDummyUser() {

        User user = new User();

        user.setName("Mallory");
        user.setAge(33);

        List<String> msg = new ArrayList<>();
        msg.add("hello jackson 1");
        msg.add("hello jackson 2");
        msg.add("hello jackson 3");

        user.setMessages(msg);

        return user;

    }

    private MockMvc mvc;

    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void getHello() throws Exception {

        MvcResult r = mvc.perform(MockMvcRequestBuilders
                .get("/")
                .accept(MediaType.APPLICATION_JSON)).andReturn();


        String jsonInString = "";
        String json = "";
        User user = createDummyUser();
        ObjectMapper mapper = new ObjectMapper();
        try {
            //Convert object to JSON string and save into file directly
            mapper.writeValue(new File("user.json"), user);

            //Convert object to JSON string
            jsonInString = mapper.writeValueAsString(user);
            System.out.println(jsonInString);

            //Convert object to JSON string and pretty print
            jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            json = ow.writeValueAsString(jsonInString);

            mvc.perform(MockMvcRequestBuilders.get("/catalogs2").accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk())


                    .andExpect(content().string(equalTo(json)));

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

测试

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM