简体   繁体   English

在 flutter 中测试 kIsWeb 常量

[英]Testing kIsWeb constant in flutter

in my code i have a lookup method:在我的代码中,我有一个lookup方法:

lookup.dart查找.dart

Future<http.Response> httpLookup(String address) {
    return kIsWeb
        ? _httpClient.get(address)
        : _httpClient.get(
            Uri.https(address, ''),
          );
  }

how can i test the kIsWeb constant during unit testing?我如何在单元测试期间测试kIsWeb常量? this is what i have tried so far but the coverage is not going though.到目前为止,这是我已经尝试过的方法,但覆盖范围并未扩大。

lookup_test.dart lookup_test.dart

@TestOn('browser')
void main (){
test('shoud test lookup', () {
    InternetLookup lookup = InternetLookup();
    when(mockInternetLookup.httpLookup(any))
        .thenAnswer((realInvocation) async => http.Response('success', 200));
    lookup.httpLookup('www.google.com');
  });
}

You can to use an Interface and to mock it.您可以使用接口并模拟它。

abstract class IAppService {
  bool getkIsWeb();
}

class AppService implements IAppService {
  bool getkIsWeb() {
    return kIsWeb;
  }
}

In the tests, you must to use like as在测试中,你必须使用 like as

class MockAppService extends Mock implements IAppService {}

... ...

when(appService.getkIsWeb())
        .thenAnswer((realInvocation) => true);

Another way would be to actually run it in a web environment with另一种方法是在 web 环境中实际运行它

flutter test --platform chrome

You can also add您还可以添加

@TestOn('browser')

at the top of your test file so your tests are only run when the platform is a browser.在你的测试文件的顶部,所以你的测试只在平台是浏览器时运行。

Look at TestOn and its README .查看TestOn及其自述文件。

Another way would be to add an optional parameter and decorate it with @visibleForTesting to override the kIsWeb constant:另一种方法是添加一个可选参数并用 @visibleForTesting 装饰它以覆盖kIsWeb常量:

Future<http.Response> httpLookup(String address, { @visibleForTesting bool isTestingForWeb = false}) {
  return kIsWeb || isTestingForWeb ? ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM