Java 弹簧启动测试:测试响应抛出“;找不到可接受的陈述“,应用程序工作正常

Java 弹簧启动测试:测试响应抛出“;找不到可接受的陈述“,应用程序工作正常,java,spring,spring-mvc,testing,spring-boot,Java,Spring,Spring Mvc,Testing,Spring Boot,我正在使用SpringBoot创建一个应用程序。当我运行应用程序并测试服务时,我得到了正确的结果 但是,当我运行测试时,如下所示: public class CatalogControllerTet { private MockMvc mvc; @Autowired private WebApplicationContext context; @Autowired private CatalogRepository catalogRepository;

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

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

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的内容

我看到了一些与我类似的问题,但它们可以追溯到响应对象没有任何getter/setter或与Jackson库有关的东西。服务启动并正确运行这一事实意味着它不是这些问题


非常感谢您在这方面提供的任何帮助。

您的控制器的外观如下所示

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\":[]}")));
    }
}
测试成功

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\":[]}")));
    }
}

如果您需要一个样板,欢迎使用my进行新的spring boot项目。您只需克隆它并运行它:

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;
    }

}
包你好;
导入com.fasterxml.jackson.core.jsongGenerationException;
导入com.fasterxml.jackson.databind.JsonMappingException;
导入com.fasterxml.jackson.databind.ObjectMapper;
导入com.fasterxml.jackson.databind.ObjectWriter;
导入org.springframework.http.MediaType;
导入org.springframework.web.bind.annotation.ResponseBody;
导入org.springframework.web.bind.annotation.RestController;
导入org.springframework.web.bind.annotation.RequestMapping;
导入org.w3c.dom.Entity;
导入java.io.File;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.List;
导入静态org.springframework.web.bind.annotation.RequestMethod.GET;
@RestController
类Hello控制器{
私有类用户{
私有字符串名称;
公共整数getAge(){
回归年龄;
}
无效设置(整数年龄){
这个。年龄=年龄;
}
私人互联网;
公共列表getMessages(){
返回消息;
}
无效设置消息(列出消息){
this.messages=消息;
}
私人列表消息;
公共字符串getName(){
返回名称;
}
void setName(字符串名称){
this.name=名称;
}
//接球手和接球手
}
私有用户createDummyUser(){
用户=新用户();
user.setName(“Mallory”);
用户设置(33);
List msg=new ArrayList();
msg.add(“hello jackson 1”);
msg.add(“hello jackson 2”);
msg.add(“hello jackson 3”);
user.setMessages(msg);
返回用户;
}
@RequestMapping(value=“/catalogs2”,products={“application/json”})
@应答器
公共字符串目录(){
字符串jsonInString=“”;
字符串json=“”;
User User=createDummyUser();
ObjectMapper mapper=新的ObjectMapper();
试一试{
//将对象转换为JSON字符串并直接保存到文件中
writeValue(新文件(“user.json”),user);
//将对象转换为JSON字符串
jsonInString=mapper.writeValueAsString(用户);
System.out.println(jsonInString);
//将对象转换为JSON字符串并打印
jsonInString=mapper.writerWithDefaultPrettyPrinter().writeValueAsString(用户);
ObjectWriter ow=新建ObjectMapper().writer().withDefaultPrettyPrinter();
json=ow.writeValueAsString(JSONInstalling);
}捕获(JsonGenerationException e){
e、 printStackTrace();
}捕获(JsonMappingException e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回json;
}
}
试验

包你好;
导入静态org.hamcrest.Matchers.equalTo;
导入静态org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
导入静态org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
导入com.fasterxml.jackson.core.jsongGenerationException;
导入com.fasterxml.jackson.databind.JsonMappingException;
导入com.fasterxml.jackson.databind.ObjectMapper;
导入com.fasterxml.jackson.databind.ObjectWriter;
导入org.junit.Before;
导入org.junit.Test;
导入org.junit.runner.RunWith;
导入org.springframework.boot.test.SpringApplicationConfiguration;
导入org.springframework.http.MediaType;
导入org.springframework.mock.web.MockServletContext;
导入org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
导入org.springframework.test.context.web.WebAppConfiguration;
导入org.springframework.test.web.servlet.MockMvc;
导入org.springframework.test.web.servlet.MvcResult;
导入org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
导入org.springframework.test.web.servlet.setup.MockMvcBuilders;
导入java.io.File;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=MockServletContext.class)
@WebAppConfiguration
公共类HelloControllerTest{
私有类用户{
私有字符串名称;
公共整数getAge(){
回归年龄;
}
无效设置(整数年龄){
这个。年龄=年龄;
}
私人互联网;
公共列表getMessages(){
返回消息;
}
无效设置消息(列出消息){
this.messages=消息;
}
私人列表消息;
公共字符串getName(){
返回名称;
}
void setName(字符串名称){
this.name=名称;
}
//接球手和接球手
}
私有用户createDummyUser(){
用户=新用户();
user.setName(“Mallor
@RunWith(SpringRunner.class)
@SpringBootTest
public class CatalogControllerITTest {
...
@RunWith(SpringRunner.class)
@SpringBootTest
@DataJpaTest
public class CatalogControllerITTest {
...