andExpect method

ResultActions andExpect({
  1. int? status,
  2. String? contentType,
  3. Map<String, String> headers = const {},
  4. Object? body,
  5. Object? json,
})

Checks the response; each argument left out is not checked.

  • status: the status code, exactly.
  • contentType: a media type compatible with the response's (application/json matches application/json;charset=utf-8).
  • headers: each listed header has exactly this value.
  • body: the body as text, equal to a String or matching a matcher.
  • json: the body decoded from JSON, equal to a value or matching a matcher (hasLength(1), containsPair('title', 'Dune')). A body that is not JSON throws a FormatException.

A failed check throws a TestFailure that names the request and shows the whole response. Spring's andExpect(status().isOk()), content().json(...) and the like, as named arguments.

Implementation

ResultActions andExpect({
  int? status,
  String? contentType,
  Map<String, String> headers = const {},
  Object? body,
  Object? json,
}) => ResultActions._(
  _result.then((result) {
    final response = result.response;
    void fail(String what, Object? expected, Object? actual) =>
        throw TestFailure(
          '${result.request.method.value} ${result.request.uri}: '
          'expected $what $expected, got $actual\n'
          'Response: ${response.statusCode} ${response.headers.toMap()}\n'
          '${response.bodyText}',
        );
    if (status != null && response.statusCode != status) {
      fail('status', status, response.statusCode);
    }
    if (contentType != null) {
      final actual = response.headers.contentType;
      if (actual == null ||
          !MediaType.parse(actual)
              .isCompatibleWith(MediaType.parse(contentType))) {
        fail('Content-Type', contentType, actual);
      }
    }
    headers.forEach((name, value) {
      if (response.headers[name] != value) {
        fail('header $name', value, response.headers[name]);
      }
    });
    if (body != null) {
      _check('body', body, response.bodyText, fail);
    }
    if (json != null) {
      _check('JSON', json, response.json, fail);
    }
    return result;
  }),
);