响应内容类型为' null'。放心例外

时间:2018-05-30 06:21:03

标签: java testing rest-assured

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

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,但无论如何都没有用。我错过了什么吗?线程甚至没有进入控制器方法

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

  

在中添加produce = MediaType.APPLICATION_JSON_UTF8_VALUE    @RequestMapping 而不是 @GetMapping

替换

 @RequestMapping(ApiUrls.SESSIONS_API)

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