i am using Mockitou package to Test my MessageBloc and the logic of my Message application in Flutter but i have common issue in all my tests mentioned in the title (The return type ‘Null’ isn’t a ‘Future<Message>’, as required by the closure’s context.) i Comment in the code where the error is
import 'package:chat/chat.dart';
import 'package:flutter_newapp/src/blocs/message/message_bloc.dart';
import 'package:flutter_newapp/src/blocs/message/message_event.dart';
import 'package:flutter_newapp/src/blocs/message/message_state.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class FakeMessageService extends Mock implements IMessageService {}
void main() {
late MessageBloc sut;
late IMessageService messageService;
User user;
setUp(() {
messageService = FakeMessageService();
user = User(
username: 'test', photoUrl: '', active: true, lastSeen: DateTime.now());
sut = MessageBloc(messageService);
});
tearDown(() => sut.close());
test('it should emit initial state before Subscription',
() => expect(sut.state, MessageInitial()));
test('should emit message sent state when message is sent', () {
final message = Message(
from: '1234',
to: '123',
timestamp: DateTime.now(),
contents: 'Hellllo');
when(messageService.send([message])).thenAnswer((_) async => null); // Here is the Error
sut.add(MessageEvent.onMessageSent([message]));
expectLater(sut.stream, emits(MessageState.sent(message)));
});
}
So if anyone have a Solution i will be So grateful
Do i have to Override the Methods of IMessageService or Something ? i think that this is the problem
2
Answers
I think
messageService.send([message])
returns a type ofFuture<Message>
, that’s why you’re getting this error.You can modify that method and set the type to
Future<Message?>
or provide a dummyFuture<Message>
value in the test itself.Because right now your method can’t return null and you are returning null from the test that’s why you’re facing the issue.
Hope it helps.
This error is occurring because the closure you are passing to then fun is not returning the correct type. The closure is expected to return a Future, but it’s returning null instead.
To resolve this error, you need to make sure that the closure you pass to then fun returns a Future that completes successfully. You can do this by returning a Future. value(null) instead of just null.