Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 内容类型未从服务器Spring设置JSON对象_Java_Json_Unit Testing_Rest_Spring Mvc - Fatal编程技术网

Java 内容类型未从服务器Spring设置JSON对象

Java 内容类型未从服务器Spring设置JSON对象,java,json,unit-testing,rest,spring-mvc,Java,Json,Unit Testing,Rest,Spring Mvc,我已经在spring中设置了一个REST应用程序,我希望应用程序从我的Java类返回JSON对象。我试图让我的单元测试将响应识别为JSON对象,但它一直失败 下面是应用程序上下文 com.livingsoup.beaconapp.data.entities.CustomerEntity org.hibernate.dialogue.mysql5dialogue 真的 这是web.xml文件 信标MVC Rest应用程序 mvc调度器 org.springframework.web.serv

我已经在spring中设置了一个REST应用程序,我希望应用程序从我的Java类返回JSON对象。我试图让我的单元测试将响应识别为JSON对象,但它一直失败

下面是应用程序上下文


com.livingsoup.beaconapp.data.entities.CustomerEntity
org.hibernate.dialogue.mysql5dialogue
真的
这是web.xml文件


信标MVC Rest应用程序
mvc调度器
org.springframework.web.servlet.DispatcherServlet
1.
mvc调度器
/
这是我的控制器

@RestController
@RequestMapping(value = "/student")
public class DataController
{
    private CustomerDOA customerDOA;

    @Autowired
    public DataController(CustomerDOA customerDOA)
    {
        this.customerDOA = customerDOA;
    }

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public @ResponseBody
    Student getData()
    {
        Student student = new Student();
        student.setName("Hello World");
        return student;
    }

    @RequestMapping(value = "/findByPhoneNumber", method = RequestMethod.GET, produces="application/json")
    public @ResponseBody CustomerEntity findByPhoneNumber()
    {
        return customerDOA.findByPhoneNumber("07966487189");
    }
这是我的实体

@Entity
@Table(name = "Customer", schema = "", catalog = "iBeaconServiceDB")
public class CustomerEntity
{
    private int id;
    private String firstName;
    private String lastName;
    private String phoneNumber;
    private String address1;
    private String address2;
    private String address3;
    private String city;
    private String postCode;

    @Id
    @Column(name = "id", nullable = false, insertable = true, updatable = true)
    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    @Basic
    @Column(name = "first_name", nullable = true, insertable = true, updatable = true, length = 255)
    public String getFirstName()
    {
        return firstName;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    @Basic
    @Column(name = "last_name", nullable = true, insertable = true, updatable = true, length = 255)
    public String getLastName()
    {
        return lastName;
    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }

    @Basic
    @Column(name = "phone_number", nullable = true, insertable = true, updatable = true, length = 25)
    public String getPhoneNumber()
    {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber)
    {
        this.phoneNumber = phoneNumber;
    }

    @Basic
    @Column(name = "address_1", nullable = true, insertable = true, updatable = true, length = 255)
    public String getAddress1()
    {
        return address1;
    }

    public void setAddress1(String address1)
    {
        this.address1 = address1;
    }

    @Basic
    @Column(name = "address_2", nullable = true, insertable = true, updatable = true, length = 255)
    public String getAddress2()
    {
        return address2;
    }

    public void setAddress2(String address2)
    {
        this.address2 = address2;
    }

    @Basic
    @Column(name = "address_3", nullable = true, insertable = true, updatable = true, length = 255)
    public String getAddress3()
    {
        return address3;
    }

    public void setAddress3(String address3)
    {
        this.address3 = address3;
    }

    @Basic
    @Column(name = "city", nullable = true, insertable = true, updatable = true, length = 255)
    public String getCity()
    {
        return city;
    }

    public void setCity(String city)
    {
        this.city = city;
    }

    @Basic
    @Column(name = "post_code", nullable = true, insertable = true, updatable = true, length = 255)
    public String getPostCode()
    {
        return postCode;
    }

    public void setPostCode(String postCode)
    {
        this.postCode = postCode;
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        CustomerEntity that = (CustomerEntity) o;

        if (id != that.id) return false;
        if (address1 != null ? !address1.equals(that.address1) : that.address1 != null) return false;
        if (address2 != null ? !address2.equals(that.address2) : that.address2 != null) return false;
        if (address3 != null ? !address3.equals(that.address3) : that.address3 != null) return false;
        if (city != null ? !city.equals(that.city) : that.city != null) return false;
        if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) return false;
        if (lastName != null ? !lastName.equals(that.lastName) : that.lastName != null) return false;
        if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) return false;
        if (postCode != null ? !postCode.equals(that.postCode) : that.postCode != null) return false;

        return true;
    }

    @Override
    public int hashCode()
    {
        int result = id;
        result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0);
        result = 31 * result + (address1 != null ? address1.hashCode() : 0);
        result = 31 * result + (address2 != null ? address2.hashCode() : 0);
        result = 31 * result + (address3 != null ? address3.hashCode() : 0);
        result = 31 * result + (city != null ? city.hashCode() : 0);
        result = 31 * result + (postCode != null ? postCode.hashCode() : 0);
        return result;
    }
}
这是我的单元测试

 public void testGetData() throws Exception
    {
        CustomerDOA customerDOA = mock(CustomerDOAImpl.class);
        DataController controller = new DataController(customerDOA);

        MockMvc mockMvc = standaloneSetup(controller).build();
        mockMvc.perform(get("/student/findByPhoneNumber"))
        .andExpect(status().isOk())
        .andExpect(content().contentType("application/json"));
    }
java.lang.AssertionError: Content type not set
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:39)
    at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:72)
    at org.springframework.test.web.servlet.result.ContentResultMatchers$1.match(ContentResultMatchers.java:80)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:153)
    at com.livingsoup.beaconapp.controllers.DataControllerTest.testGetData(DataControllerTest.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
这是我从单元测试中得到的错误

 public void testGetData() throws Exception
    {
        CustomerDOA customerDOA = mock(CustomerDOAImpl.class);
        DataController controller = new DataController(customerDOA);

        MockMvc mockMvc = standaloneSetup(controller).build();
        mockMvc.perform(get("/student/findByPhoneNumber"))
        .andExpect(status().isOk())
        .andExpect(content().contentType("application/json"));
    }
java.lang.AssertionError: Content type not set
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:39)
    at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:72)
    at org.springframework.test.web.servlet.result.ContentResultMatchers$1.match(ContentResultMatchers.java:80)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:153)
    at com.livingsoup.beaconapp.controllers.DataControllerTest.testGetData(DataControllerTest.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
这是从我的单元测试中打印出来的响应,我无法理解我做错了什么。为什么我的单元测试不能识别我的JSON输出

MockHttpServletRequest:
         HTTP Method = GET
         Request URI = /student/findByPhoneNumber
          Parameters = {}
             Headers = {}

             Handler:
                Type = com.livingsoup.beaconapp.controllers.DataController
              Method = public com.livingsoup.beaconapp.data.entities.CustomerEntity com.livingsoup.beaconapp.controllers.DataController.findByPhoneNumber()

               Async:
   Was async started = false
        Async result = null

  Resolved Exception:
                Type = null

        ModelAndView:
           View name = null
                View = null
               Model = null

            FlashMap:

MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

从我看到的情况来看,您的配置看起来不错

但是您缺少Accept头,我不确定spring mvc是否需要这个头集来设置内容类型。但是您完全可以将spring配置为忽略accept头

contentNegotiationManagerFactoryBean.setIgnoreAcceptHeader()
这是值得一试的,或者只是设置标题

mockMvc.perform(get('/..').accept(MediaType.APPLICATION_JSON));

我设置的测试类不正确,我没有在测试类的顶部添加注释,我还应该在控制器中添加@AutoWired注释,我还添加了doSetup方法(参见下面的示例)


我已经在测试中设置了标题,它将显示在输出中,内容类型仍然没有设置。在哪里添加contentNegotiationManagerFactoryBean.setIgnoreAcceptHeader()?我对springYou非常陌生,您将其设置为bean的属性:只看到您的主体也是空的,这表明没有任何内容被序列化。您的类路径中是否有jackson mapper asl?我现在已在contentNegotiationManager上设置了属性,并已将Dependency jackson mapper asl 1.9.13添加到我的pom.xml文件中。但是我不应该在测试类的setup方法中初始化hibernate