Reputation: 2742
I am trying to ping a server from my code. I am using StreamController<ConnectionState>
to check for internet connectivity every 5 (1 in below test) second. The case for the test is passing invalid uri. I want to test that there is an error.
I have tried expectLater(connectionStream, emitsError(ConnectionError));
in the test. However, I am getting the below error.
Error:
Expected: should emit an error that Type:<ConnectionError>
Actual: <Instance of '_ControllerStream<ConnectionState>'>
Which: emitted ! Instance of 'ConnectionError'
File: connection.dart
import 'dart:async';
import 'dart:io';
import 'package:http/http.dart' as http;
class ConnectionController {
String serverUrl;
Duration repeatInterval;
Timer? _timer;
late final StreamController _controller;
Stream get stream => _controller.stream;
ConnectionController({
this.serverUrl = 'https://google.com',
this.repeatInterval = const Duration(
seconds: 5,
),
}) {
_controller = StreamController<ConnectionState>(
onListen: () {
_timer ??= Timer.periodic(repeatInterval, (timer) async {
try {
Uri parsedUri = Uri.parse(serverUrl);
final response = await http.get(parsedUri);
if (response.statusCode == HttpStatus.ok) {
_controller.add(ConnectionState(isConnected: true));
} else {}
} catch (error, stacktrace) {
if (error is ArgumentError || error is SocketException) {
print(error.toString());
_controller.addError(
ConnectionError(
errorType: ConnectionErrorType.invalidServerUrl,
errorDescription: error.toString()),
);
}
print(error);
print(error.runtimeType);
print(stacktrace);
}
});
},
onCancel: () {
_timer?.cancel();
},
);
}
}
class ConnectionState {
bool isConnected;
ConnectionState({
required this.isConnected,
});
}
class ConnectionError extends Error {
ConnectionErrorType errorType;
String errorDescription;
ConnectionError({
required this.errorType,
required this.errorDescription,
});
}
enum ConnectionErrorType {
invalidServerUrl,
}
File: tests\connection_test.dart
import 'package:connection_info/connection.dart';
import 'package:flutter_test/flutter_test.dart';
import 'mocks/connection_error.dart';
void main() {
group('Connection Controller tests', () {
test('send invalid server url and get error', () async {
var connectionError = MockConnectionError();
final controller = ConnectionController(
serverUrl: 'http://asdom',
repeatInterval: Duration(seconds: 1),
);
Stream connectionStream = controller.stream;
expectLater(connectionStream, emitsError(ConnectionError));
});
});
}
I want to validate that the stream has received the error. How can I test properly for the error?
Upvotes: 1
Views: 1039
Reputation: 46
I think you should add a matcher in emitsErros, so you can fix like this
expectLater(connectionStream, emitsError(isA<ConnectionError>());
Upvotes: 3