为什么我在这个post命令中得到400状态?

smdnsysy  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(431)

当我用restcontroller重新运行rest-assure测试时,我得到以下错误消息:

java.lang.AssertionError: 1 expectation failed.
Expected status code <201> but was <400>

我的控制器看起来像这样

package org.steinko.restapi;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.GetMapping;

@RestController
public class MessageController {

      @PostMapping("/message")
      public Message newMessage( @RequestBody Message aMessage) {
            return aMessage ; 
        }

      @GetMapping("/message")
      public Message getMessage( ) {
            return new Message("get message"); 
        }

}

消息类类似于这个包org.steinko.restapi;

public class Message {

    private String message;

    public Message (String aMessage) {
        message = aMessage;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

其余的api测试如下所示

package tutorial;

import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
import static org.hamcrest.Matchers.equalTo;

public class MessageTest {

    @Test
    public void shouldStoreMessage() {

       String url =  "http://localhost:8080/message";   
       Message message = new Message("message");

       given()
         .contentType("application/json")
         .body(message)
       .when()
          .post(url)
       .then()
         .statusCode(201); 
    }

如何修复此错误?

qfe3c7zg

qfe3c7zg1#

补充

implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.0'
    implementation 'com.fasterxml.jackson.core:jackson-annotations:2.12.0'
    implementation 'com.fasterxml.jackson.core:jackson-core:2.12.0'
    implementation 'com.google.code.gson:gson:2.8.6'

对于gradle中的dependecies,这修复了错误

相关问题