suppose I have a widget A and in the initState() lifecycle method of that widget i am calling a function
class A extends StatefulWidget{
// the usual dart code
}
class _AState extends State<A>{
Service B = Service();
int counterId = 0;
void initState() {
super.initState();
B.initialize();
_findId();
}
@override
void dispose() {
super.dispose();B
}
Future<void> _findId() async{
getfindId(
(value) {
setState(() {counterId = value;});
}
);
}
void getFindId() async{
String uri = "uri-string";
String args = "arguments-required";
try{
await B.getIdValue(uri , args , (response){
Map<String, dynamic> jsonResponse = jsonDecode(response);
int findIdValue = jsonResponse['vault']['findId'];
callback(findIdValue);
});
}
catch(e){
print('error reported : $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body : Center(
child : Text(" the find id is : $counterId");
)
);
}
the objective is to get the counterId value using a service
and for this operation I have a test case to check if the service is called and counterId value is updated.
@GenerateMocks([B])
void main(){
group (" checking the service to get counteriD value" , (WidgetTester tester) async{
final b = MockB();
final response = {"vault": {"findId": 42}}
when(b.getIdValue(any, any, any)).thenReturn((_) async =>future.value(response);
await tester.pumpWidget(A());
await A._findId();
expect(A.counter , 42);
}
}
in the test case i wrote – the idea is to pump the A widget and call the _findId but it is getting invoked inside the initState method. so i am guessing it gets call when I pump my widget into testing , so i am providing an implementation of the B.getIdValue method but this function calls a callback at the end of its execution .
How to handle this callback in the when method of unit testing ? also why is A._findId();
remains undefined ?
error i got when i tried to define when method –
when(b.getIdValue(any, any, any)).thenReturn((_) async =>Future.value(response);
Error: The argument type 'Future<String> Function(dynamic)' can't be assigned to the parameter type 'bool'.