标签: dart-mock

如何为包含子字符串的字符串创建匹配器,同时忽略大小写

我正在使用 mockito 编写一个单元测试来模拟依赖项并检查我们是否使用正确的参数调用它。我们应该传入一个字符串,因此我尝试匹配该函数参数,但不会对整个字符串进行断言,以防我们更改措辞。所以我只想匹配消息中的一个词,但该词可能位于句子的开头或中间,因此它可能以大写开头。

dart 匹配器具有equalsIgnoringCasecontains,但我找不到处理这两者的匹配器,例如 containsIgnoringCase。有没有办法检查子字符串,同时忽略匹配器中的大小写?

dart dart-unittest dart-mock

5
推荐指数
2
解决办法
5292
查看次数

Dart 中的 Mock http.Client 给出异常

我在测试发出 http 请求的类时遇到问题。我想模拟客户端,以便每次客户端发出请求时,我都可以用模拟响应进行回答。目前我的代码如下所示:

  final fn = MockClientHandler;
  final client = MockClient(fn as Future<Response> Function(Request));

  when(client.get(url)).thenAnswer((realInvocation) async =>
    http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
Run Code Online (Sandbox Code Playgroud)

但是,当我运行测试时,出现以下异常: type '_FunctionType' is not a subtype of type '(Request) => Future<Response>' in type cast test/data_retrieval/sources/fitbit_test.dart 26:32 main

根据 Flutter/Dart Mockito 应该这样使用:

 final client = MockClient();

  // Use Mockito to return a successful response when it calls the
  // provided http.Client.
  when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
      .thenAnswer((_) async => http.Response('{"userId": 1, "id": 2, "title":"mock"}', 200));
Run Code Online (Sandbox Code Playgroud)

在示例中,客户端是在没有参数的情况下进行模拟的,但我想这已经发生了变化,因为 MockClient 的文档现在也接受参数。我不知道为什么会发生这个异常,并且在互联网上找不到任何内容,所以我想知道这里是否有人知道为什么会发生这个异常。

mockito dart dart-mock dart-http

4
推荐指数
1
解决办法
2737
查看次数

使用Dart模拟HTTP响应

我一直在研究新的API包装器,并且不希望每次运行单元测试时都调用API.因此,作为描述在这里,我嘲笑它.

我最初认为我嘲笑它的方式有问题,但似乎问题出在其他地方.

我想要完成的事情非常简单.当我的单元测试运行时,我想返回一个值,好像我已经出去从我正在集成的外部API获取信息.

我使用http.Client作为可选参数初始化我的类,所以我可以在单元测试运行时将其传入:

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

Future apiRequest(String resource, [Map<String, String> body]) {
    var url = buildBaseUrl(resource).toString();
    var request = new http.Request('POST', Uri.parse(url));
    request.bodyFields = body;
    return this._httpClient.send(request).then((response) => response.stream.bytesToString().then((value) => value.toString()));
}
Run Code Online (Sandbox Code Playgroud)

在我的单元测试中,我创建了以下模拟类:

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

class HttpResponseMock extends Mock implements http.Response {
    noSuchMethod(i) => super.noSuchMethod(i); …
Run Code Online (Sandbox Code Playgroud)

mocking dart dart-unittest dart-mock

3
推荐指数
1
解决办法
1493
查看次数

标签 统计

dart ×3

dart-mock ×3

dart-unittest ×2

dart-http ×1

mocking ×1

mockito ×1