簡體   English   中英

使用MockMVC測試Spring RESTful put方法失敗

[英]test Spring RESTful put method failed using MockMVC

我想對基於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 + '\'' +
            '}';
    }
}

看起來測試正在使用默認配置,根據Spring Data REST ,該配置將返回204 No Content 參考文檔

5.1.1。 默認狀態碼

對於公開的資源,我們使用一組默認狀態代碼:

  • 200 OK-用於簡單的GET請求。

  • 201已創建-用於創建新資源的POST和PUT請求。

  • 204 No Content-對於PUT,PATCH和DELETE請求,如果配置設置為不返回資源更新的響應主體(RepositoryRestConfiguration.returnBodyOnUpdate)。 如果配置值設置為包括對PUT的響應,則將返回200 OK進行更新,對於通過PUT創建的資源將返回201 Created。

如果配置值(RepositoryRestConfiguration.returnBodyOnUpdate和RepositoryRestConfiguration.returnBodyCreate)明確設置為null,則將使用HTTP Accept標頭來確定響應代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM