问题
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