简体   繁体   English

如何在视图模型中测试提供者

[英]How to test provider in view model

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无论如何我可以测试这个,或者我必须重构代码

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.您应该重构您的代码,如果该函数在 ViewModel 中,问题在于它不应该对表示层一无所知或尽可能少。 So it should NOT depend on the BuildContext , instead pass in the needed dependencies either directly to the function:所以它不应该依赖于BuildContext ,而是直接将所需的依赖项传递给函数:

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.或者将它注入到 ViewModel 构造函数中,这样您就可以将 viewModel 与 UI 和PersonProvider ,现在可以将其作为模拟传递进行测试。

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.如果您所指的视图模型实际上只是一个演示者,您可以进行小部件测试并为小部件树提供 Mock PersonProvider实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM