How do I stub a function that does not belong to a class, during a widget test?

…衆ロ難τιáo~ 提交于 2020-05-15 05:43:12

问题


I am creating a flutter app that uses the native camera to take a photo, using the official flutter camera package (https://pub.dev/packages/camera). The app opens up a modal that loads a CameraPreview based on the the result of the availableCameras function from the package and a FloatingActionButton which takes a photo when pressed. While creating a widget test for this modal, I can not figure out how to stub the availableCameras function to return what I want during tests.

I tried using the Mockito testing package, but this only supports mocking classes. Since this function does not belong to a class, I cannot mock it.

The availableCameras function returns a list of cameras that the device has. I want to be able to control what comes back from this function, so that I may test how my widget reacts to different cameras. What is the proper way to have this function return what I want during a widget test?


回答1:


Mockito can mock functions too. In dart, functions are classes with a call method.

You can, therefore, use Mockito as usual, with an abstract call method:

class MockFunction extends Mock {
  int call(String param);
}

This example represents a int Function(String param).

Which means you can then do:

final int Function(String) myFn = MockFunction();
when(myFn('hello world')).thenReturn(42);

expect(myFn('hello world'), equals(42));



回答2:


In this very specific situation, you can mock the method channel call handler.

const cameraMethodChannel = MethodChannel('plugins.flutter.io/camera');

setUpAll(() {
  cameraMethodChannel.setMockMethodCallHandler(cameraCallHandler);
});

tearDownAll(() {
  cameraMethodChannel.setMockMethodCallHandler(null);
});

Future<dynamic> cameraCallHandler(MethodCall methodCall) async {
  if (methodCall.method == 'availableCameras') return yourListOfCameras;
}


来源:https://stackoverflow.com/questions/57582592/how-do-i-stub-a-function-that-does-not-belong-to-a-class-during-a-widget-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!