Mocking with Dart

白昼怎懂夜的黑 提交于 2019-12-23 03:42:17

问题


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.


回答1:


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'));

  });
}


来源:https://stackoverflow.com/questions/24208588/mocking-with-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!