I have a view model that a view uses, i want to write a unit test for one of the functions which contains a provider. The function is something like this
Future<String> onSubmit(BuildContext context) async {
PersonProvider personProvider = Provider.of<PersonProvider>(context,listen: false);
String userId = personProvider.user.id;
isLoading = true;
return 'hello';
});}
Is there anyway I can test this, or I have to refactor code
CodePudding user response:
You should refactor your code, if that function is in a ViewModel the problem is that it should not know nothing or as little as possible of the presentation layer. So it should NOT depend on the BuildContext
, instead pass in the needed dependencies either directly to the function:
Future<String> onSubmit(PersonProvider personProvider) async {
String userId = personProvider.user.id;
isLoading = true;
return 'hello';
});}
Or inject it to the ViewModel constructor, that way you decouple your viewModel from the UI, and from PersonProvider
, which can now be passed as a mock for testing.
If what you are referring to as viewmodel is really just a presenter you could do widget tests and providr a Mock PersonProvider
implementation to the widget tree.