deserializeBody test
This commit is contained in:
parent
bcfaf04dda
commit
673754ac84
2 changed files with 20 additions and 2 deletions
|
@ -221,14 +221,14 @@ abstract class RequestContext<RawRequest> {
|
|||
/// Returns as `true` if the client's `Accept` header indicates that it will accept any response content type.
|
||||
bool get acceptsAll => _acceptsAllCache ??= accepts('*/*');
|
||||
|
||||
/// Shorthand for deserializing a body.
|
||||
/// Shorthand for deserializing [bodyAsMap], using some transformer function [f].
|
||||
Future<T> deserializeBody<T>(FutureOr<T> Function(Map) f,
|
||||
{Encoding encoding = utf8}) async {
|
||||
await parseBody(encoding: encoding);
|
||||
return await f(bodyAsMap);
|
||||
}
|
||||
|
||||
/// Shorthand for decoding a body.
|
||||
/// Shorthand for decoding [bodyAsMap], using some [codec].
|
||||
Future<T> decodeBody<T>(Codec<T, Map> codec, {Encoding encoding = utf8}) =>
|
||||
deserializeBody(codec.decode, encoding: encoding);
|
||||
|
||||
|
|
|
@ -61,6 +61,14 @@ void main() {
|
|||
expect(req.bodyAsList, ['foo', 'bar']);
|
||||
});
|
||||
|
||||
test('deserializeBody', () async {
|
||||
var req = await request(
|
||||
asJson: true, bodyFields: {'text': 'Hey', 'complete': false});
|
||||
var todo = await req.deserializeBody(Todo.fromMap);
|
||||
expect(todo.text, 'Hey');
|
||||
expect(todo.completed, false);
|
||||
});
|
||||
|
||||
test('throws when body has not been parsed', () async {
|
||||
var req = await request(parse: false);
|
||||
expect(() => req.bodyAsObject, throwsStateError);
|
||||
|
@ -97,3 +105,13 @@ void main() {
|
|||
throwsStateError);
|
||||
});
|
||||
}
|
||||
|
||||
class Todo {
|
||||
String text;
|
||||
bool completed;
|
||||
|
||||
Todo({this.text, this.completed});
|
||||
|
||||
static Todo fromMap(Map m) =>
|
||||
Todo(text: m['text'] as String, completed: m['complete'] as bool);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue