【问题标题】:Response Content-Type was 'null'. Rest assured exception响应内容类型为“空”。放心例外
【发布时间】:2018-05-30 06:21:03
【问题描述】:

我对放心有问题。我收到以下错误

java.lang.IllegalStateException: Cannot parse object because no supported Content-Type was specified in response. Content-Type was 'null'.

我的休息控制器如下所示

@Slf4j
@RestController
@RequestMapping(ApiUrls.SESSIONS_API)
@RequiredArgsConstructor
public class SessionsApi {

    private final SessionsService sessionsService;

    @GetMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<SessionDto> sessions(@AuthenticationPrincipal CryptoUser user,
                                     @RequestParam(required = false, defaultValue = "false") boolean includeExpired) {
        log.info("User sessions of user [id {} username {}]", user.getUserId(), user.getUsername());


        return sessionsService.getSessionsOfUser(user, includeExpired);
    }

和测试

SessionDto[] sessionDtos = given().mockMvc(mvc)
        .log().all()
        .header("Accept","application/json")
        .get(ApiUrls.SESSIONS_API)
        .then()
        .extract()
        .as(SessionDto[].class);

我得到放心的日志

Request method: GET
Request URI:    http://localhost:8080/api/sessions?includeExpired=true
Proxy:          <none>
Request params: includeExpired=true
Query params:   <none>
Form params:    <none>
Path params:    <none>
Headers:        Content-Type=application/json
                Accept=application/json
Cookies:        <none>
Multiparts:     <none>
Body:           <none>

我尝试在 getmapping 中添加produce = MediaType.APPLICATION_JSON_VALUE,但无论如何都没有用。我错过了什么吗?线程甚至没有进入控制器方法

【问题讨论】:

    标签: java testing rest-assured


    【解决方案1】:

    如果您的内容类型为 null,您可以尝试这样的操作

    given().mockMvc(mvc)
        .log().all()
        .header("Accept","application/json")
        .get(ApiUrls.SESSIONS_API)
        .then()
        .contentType(isEmptyOrNullString())//This is where you handle null
        .extract()
        .as(SessionDto[].class);
    

    此链接也可能有用:https://github.com/rest-assured/rest-assured/issues/636

    【讨论】:

      【解决方案2】:

      在中添加产生 = MediaType.APPLICATION_JSON_UTF8_VALUE @RequestMapping 而不是 @GetMapping。

      替换

       @RequestMapping(ApiUrls.SESSIONS_API)
      

      与

      @RequestMapping(value = ApiUrls.SESSIONS_API, produces = {
          MediaType.APPLICATION_JSON_VALUE })
      

      【讨论】:

      • 不,没有用。无论如何,RestController 默认生成 JSON
      猜你喜欢
      • 2010-09-28
      • 2011-08-31
      • 1970-01-01
      • 2011-01-21
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-28
      相关资源
      最近更新 更多