1

I've been trying to get my head around the mocking library in dart, but it seems I've still not got it.

In my library, I have an HTTP request to an external resource, which I would like to mock as to not rely on the external resource all the time.

The main class in my library looks like this:

SampleClass(String arg1, String arg2, [http.Client httpClient = null]) {
    this._arg1 = arg1;
    this._arg2 = arg2;
    _httpClient = (httpClient == null) ? http.Request : httpClient;
}

So I have prepared my class to receive http.client as an argument, as this is what I would like to mock.

So in my unit tests file I've created:

class HttpClientMock extends Mock implements http.Client {
  noSuchMethod(i) => super.noSuchMethod(i);
}

And on my unit test I have done:

var mockHttpClient = new HttpClientMock()
        ..when(callsTo('send')).alwaysReturn("this is a test");

I would then expect that every time I called "send" from my library, which has been instanciated in my unit tests with the optional "httpClient", that it would return "this is a test". I'm pretty sure I'm missing somethign very big here, but can't quite put my finger on what.

Any help appreciated.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Marcos Placona
  • 21,468
  • 11
  • 68
  • 93

1 Answers1

3

I'm not sure what you are missing because your example works for me:

void main() {
  test('bla', () {
    var mockHttpClient = new HttpClientMock()
            ..when(callsTo('send')).alwaysReturn("this is a test");

    http.Request req = new http.Request('POST', Uri.parse('http://www.google.com'));
    var s = mockHttpClient.send(req);
    print(s);
    expect(mockHttpClient.send(req), equals('this is a test'));

  });
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • You are right. Thanks again. I was stuck in a different problem and though there was a problem with what I was doing. I will post another question with the real problem I'm stuck with :-) – Marcos Placona Jun 14 '14 at 21:12