使用MockMVC测试Spring RESTful put方法失败

时间:2016-06-25 17:04:33

标签: java spring rest unit-testing

我想对基于Spring Framework的RESTful API使用单元测试,我使用mysql来保存我的数据并使用PagingAndSortingRepository来实现我的RESTful API,这是我的测试代码:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = SpringMvcApplication.class)
    @WebAppConfiguration
    public class CustomerRepositoryTests {


        private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
        SUBTYPE);

        private static final String SUBTYPE = "hal+json";

        private MockMvc mockMvc;
        @Autowired
        private WebApplicationContext webApplicationContext;

        @Autowired
        private CustomerRepository customerRepository;

        private long setupId;

        @Before
        public void setup() {
            this.mockMvc = webAppContextSetup(webApplicationContext)
            .apply(springSecurity())
            .build();
            customerRepository.deleteAll();
            Customer customer = customerRepository.save(new Customer("userId", "my mobile", "my address", "my contactName"));
            setupId = customer.getId();
        }


        @Test
        //// FIXME: 6/26/16 Status Code is always 204, not 200!
        public void changeCustomer() throws Exception {
            mockMvc.perform(put("/api" + "/customers/{id}", setupId)
            .content(TestUtil.objToJson(new Customer("my new userId", "my new mobile", "my new address", "my new contactName")))
            .contentType(contentType))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.userId", is("my new userId")))
            .andExpect(jsonPath("$.contactName", is("my new contactName")))
            .andExpect(jsonPath("$.mobile", is("my new mobile")))
            .andExpect(jsonPath("$.address", is("my new address")));
        }
}

我的测试总是失败并说:

    java.lang.AssertionError: Status 
    Expected :200
    Actual   :204

但是当我运行我的应用程序并使用如下命令时:

     curl -X PUT -H "Content-Type:application/hal+json" -d '{ "userId": "Bilbo", "mobile": "Baggins", "contactName":"my new contact", "address":"new address" }' http://localhost:8080/api/customers/1

我的服务器返回状态代码200并成功更新数据。 我搜索了一会儿却对此一无所知。

编辑: 这是我的CustomerRepository:

    public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {
    }

客户:

@Data
@Entity
@Table(name = "customer")
public class Customer {
    @Id
    @GeneratedValue()
    private Long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created", nullable = false)
    private Date created;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated", nullable = false)
    private Date updated;

    @Version
    @JsonIgnore
    private Long version;

    @NotNull
    private String userId;

    //TODO: Limit type to 1, 2, 3 or 4
    private int type;

    private String companyName;

    private String phone;

    @NotNull
    private String mobile;

    @NotNull
    private String address;

    private String zip;

    @NotNull
    private String contactName;


    private String email;


    public Customer(String userId, String mobile, String address, String contactName) {
        this(userId, 1, null, null, mobile, address, null, contactName, null);
    }

    public Customer() {}


    public Customer(Long id, String userId, String mobile, String address, String contactName) {
        this(id, userId, 1, null, null, mobile, address, null, contactName, null);
    }

    public Customer(Long id, String userId, int type, String companyName, String phone, String mobile, String address, String zip, String contactName, String email) {
        this.id = id;
        this.userId = userId;
        this.type = type;
        this.companyName = companyName;
        this.phone = phone;
        this.mobile = mobile;
        this.address = address;
        this.zip = zip;
        this.contactName = contactName;
        this.email = email;
    }


    public Customer(String userId, int type, String companyName, String phone, String mobile, String address, String zip, String contactName, String email) {
        this.userId = userId;
        this.type = type;
        this.companyName = companyName;
        this.phone = phone;
        this.mobile = mobile;
        this.address = address;
        this.zip = zip;
        this.contactName = contactName;
        this.email = email;
    }  

    public Long getId() {
        return id;
    }


    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getMobile() {
        return mobile;
    } 

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }



    @PrePersist
    protected void onCreate() {
        updated = created = new Date();
    }

    @PreUpdate
    protected void onUpdate() {
        updated = new Date();
    }



    @Override
    public String toString() {
        return "Customer{" +
            "id=" + id +
            ", creation time=" + created +
            ", userId=" + userId +
            ", type=" + type +
            ", companyName='" + companyName + '\'' +
            ", phone='" + phone + '\'' +
            ", mobile='" + mobile + '\'' +
            ", address='" + address + '\'' +
            ", zip='" + zip + '\'' +
            ", contactName='" + contactName + '\'' +
            ", email='" + email + '\'' +
            '}';
    }
}

1 个答案:

答案 0 :(得分:2)

看起来测试使用默认配置,根据Spring Data REST - Reference Documentation

返回204 No Content
  

5.1.1. Default status codes

     

对于公开的资源,我们使用一组默认状态代码:

     
      
  • 200 OK - 对于普通的GET请求。

  •   
  • 201 Created - 用于创建新资源的POST和PUT请求。

  •   
  • 204 No Content - 如果配置设置为不返回资源的响应主体,则为PUT,PATCH和DELETE请求   更新(RepositoryRestConfiguration.returnBodyOnUpdate)。如果   配置值设置为包括PUT的响应,200 OK即可   返回更新,201将为资源返回Created   通过PUT创建。

  •   
     

如果配置值   (RepositoryRestConfiguration.returnBodyOnUpdate和   RepositoryRestConfiguration.returnBodyCreate)被显式设置为   null,将使用HTTP Accept标头的存在来确定   响应代码。