'Testing kIsWeb constant in flutter
in my code i have a lookup method:
lookup.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? this is what i have tried so far but the coverage is not going though.
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');
});
}
Solution 1:[1]
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
class MockAppService extends Mock implements IAppService {}
...
when(appService.getkIsWeb())
.thenAnswer((realInvocation) => true);
Solution 2:[2]
Another way would be to add an optional parameter and decorate it with @visibleForTesting to override the kIsWeb constant:
Future<http.Response> httpLookup(String address, { @visibleForTesting bool isTestingForWeb = false}) {
return kIsWeb || isTestingForWeb ? ...
}
Solution 3:[3]
Another way would be to actually run it in a web environment with
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Gpack |
| Solution 3 | Valentin Vignal |
