Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock server response - client on server side

I'm trying dart and I'm writing a client on the server side :

new HttpClient().post(InternetAddress.LOOPBACK_IP_V4.host, 7474, '/path').then((HttpClientRequest request) {
request.headers.contentType = ContentType.JSON;
request.headers.add(HttpHeaders.ACCEPT, ContentType.JSON);
request.write(JSON.encode(jsonData));

return request.close();
}).then((HttpClientResponse response) {
response.transform(UTF8.decoder).listen((contents) {
  _logger(contents);
  // stuff
});
});

and I would like to mock the server response.

What is the best solution ?

  • Create a server in my test class that will return the value I expect ?
  • or mock the HttpClientResponse ?

Thanks for your help ! (code would be greatly appreciated ;D)

like image 557
matth3o Avatar asked Sep 06 '14 17:09

matth3o


People also ask

How do you respond to a mock server?

To mock a server response, enable the Rules tab, set a rule, and execute the request that will trigger that rule. To create and test a rule: Select the Rules tab and click the Add New Rule button. As a result, the Rule Builder will be opened.

How do I mock an HTTP server?

Get Started Creating a Mock HTTP Server Test data generation. Configuration as code. Automated deployment and hosting of your mocks from your GitHub repository. Run locally.


1 Answers

The http packages provides support for this.

See http://www.dartdocs.org/documentation/http/0.11.1+1/index.html#http/http-testing for examples.

import 'dart:convert';
import 'package:http/testing.dart';

var client = new MockClient((request) {
  if (request.url.path != "/data.json") {
    return new Response("", 404);
  }
  return new Response(JSON.encode({
    'numbers': [1, 4, 15, 19, 214]
  }, 200, headers: {
    'content-type': 'application/json'
  });
};
like image 138
Günter Zöchbauer Avatar answered Sep 25 '22 06:09

Günter Zöchbauer