在 flutter 中测试 kIsWeb 常量

Abi*_*ina 6 unit-testing dart flutter

在我的代码中我有一个lookup方法:

查找.dart

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

kIsWeb在单元测试期间如何测试常量?这是我到目前为止所尝试过的,但报道并未进行。

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');
  });
}
Run Code Online (Sandbox Code Playgroud)

Fil*_*nio 5

您可以使用接口并模拟它。

abstract class IAppService {
  bool getkIsWeb();
}

class AppService implements IAppService {
  bool getkIsWeb() {
    return kIsWeb;
  }
}
Run Code Online (Sandbox Code Playgroud)

在测试中,您必须使用 like as

class MockAppService extends Mock implements IAppService {}
Run Code Online (Sandbox Code Playgroud)

...

when(appService.getkIsWeb())
        .thenAnswer((realInvocation) => true);
Run Code Online (Sandbox Code Playgroud)