嘲笑与箭 [英] Mocking with Dart

查看:225
本文介绍了嘲笑与箭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在我的图书馆里,我在图书馆里,有一个HTTP请求到外部资源,我想嘲笑为不依赖外部资源所有的时间。



我的库中的主类看起来像this:

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


$ b $ p

所以我已经准备好我的类接收http.client作为参数,这是我想嘲笑。



所以在我的单元测试文件中我创建了:

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

在我的单元测试中,我做了:

  var mockHttpClient = new HttpClientMock()
..when(callsTo('send'))。alwaysReturn这是一个测试);

然后我会期望每次我从我的库中调用发送我的单元测试与可选的httpClient,它会返回这是一个测试。我很确定我在这里失去了很大的地方,但是不能把我的手指放在什么上。



任何帮助赞赏。

解决方案

我不确定你缺少什么,因为你的例子适用于我:

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

http.Request req = new http.Request('POST',Uri.parse //www.google.com'));
var s = mockHttpClient.send(req);
print(s);
expect(mockHttpClient.send(req),equals这是一个测试'));

});
}


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.

解决方案

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

  });
}

这篇关于嘲笑与箭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆