Sub topic 16
Testing and verifying on real devices
This chapter assumes you have finished the earlier chapters. You should know how image_picker returns an XFile, how a CameraController is created and disposed, and how permission failures surface as exceptions. Here you will learn which parts of camera and picker code you can test automatically and which you must check on hardware.
What you can and cannot test automatically
Both plugins call native code through platform channels. A plain flutter test run happens on your development machine, with no camera, no gallery, and no permission dialog. If your widget calls ImagePicker().pickImage(...) directly in a test, the call has no platform to answer it, and the test fails with a MissingPluginException.
The solution is to split the work into two layers:
- Your own logic, which decides what to do with a result, an error, or a cancelled pick. You can test this with fast unit and widget tests.
- The plugin and platform behavior, which includes permission dialogs, the real camera hardware, and the app lifecycle. You can only verify this on a device or emulator.
Put the plugin behind a small interface
Do not let widgets call the plugin directly. Define an interface that describes what your app needs, then write one thin class that forwards to the plugin. A test can then supply a fake in place of that class.
// lib/photo_source.dart
import 'package:image_picker/image_picker.dart';
abstract class PhotoSource {
Future<XFile?> pickFromGallery();
Future<XFile?> takePhoto();
}
class ImagePickerPhotoSource implements PhotoSource {
ImagePickerPhotoSource([ImagePicker? picker])
: _picker = picker ?? ImagePicker();
final ImagePicker _picker;
@override
Future<XFile?> pickFromGallery() =>
_picker.pickImage(source: ImageSource.gallery, imageQuality: 85);
@override
Future<XFile?> takePhoto() =>
_picker.pickImage(source: ImageSource.camera);
}ImagePickerPhotoSource holds no logic, so there is little in it that can break. Everything that can go wrong in your own code lives in the class that uses the interface.
Write the logic that you will test
This controller handles three outcomes: a picked photo, a cancelled pick (null), and a failure reported as a PlatformException.
// lib/avatar_controller.dart
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'photo_source.dart';
class AvatarController extends ChangeNotifier {
AvatarController(this._source);
final PhotoSource _source;
XFile? photo;
String? error;
Future<void> choose({required bool useCamera}) async {
try {
final result = useCamera
? await _source.takePhoto()
: await _source.pickFromGallery();
if (result != null) {
photo = result;
error = null;
}
} on PlatformException catch (e) {
error = e.code == 'camera_access_denied'
? 'Camera permission denied'
: 'Could not open the picker';
}
notifyListeners();
}
}A cancelled pick leaves the previous photo in place. That is a deliberate choice, and the tests below will pin it down.
Test with a fake
A fake is a hand-written class that returns whatever the test tells it to. You do not need a mocking package for this.
// test/fake_photo_source.dart
import 'package:image_picker/image_picker.dart';
import 'package:photo_demo/photo_source.dart';
class FakePhotoSource implements PhotoSource {
FakePhotoSource({this.gallery, this.camera, this.throwOnCamera});
final XFile? gallery;
final XFile? camera;
final Exception? throwOnCamera;
@override
Future<XFile?> pickFromGallery() async => gallery;
@override
Future<XFile?> takePhoto() async {
if (throwOnCamera != null) throw throwOnCamera!;
return camera;
}
}// test/avatar_controller_test.dart
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_demo/avatar_controller.dart';
import 'fake_photo_source.dart';
void main() {
test('stores the picked photo', () async {
final controller = AvatarController(
FakePhotoSource(gallery: XFile('/tmp/cat.jpg')),
);
await controller.choose(useCamera: false);
expect(controller.photo?.name, 'cat.jpg');
expect(controller.error, isNull);
});
test('keeps the old photo when the user cancels', () async {
final controller = AvatarController(
FakePhotoSource(gallery: XFile('/tmp/cat.jpg')),
);
await controller.choose(useCamera: false);
final cancelling = AvatarController(FakePhotoSource());
cancelling.photo = controller.photo;
await cancelling.choose(useCamera: false);
expect(cancelling.photo?.name, 'cat.jpg');
});
test('reports a denied camera permission', () async {
final controller = AvatarController(
FakePhotoSource(
throwOnCamera: PlatformException(code: 'camera_access_denied'),
),
);
await controller.choose(useCamera: true);
expect(controller.photo, isNull);
expect(controller.error, 'Camera permission denied');
});
}XFile('/tmp/cat.jpg') does not need a real file. The name getter reads only the path string. If a test needs to read bytes, write a temporary file in the test and delete it afterwards.
Test the widget without rendering the image
Image.file reads from disk, which makes widget tests slow and brittle. In a widget test, show something simple that proves the right file arrived, such as its name.
// lib/avatar_screen.dart
import 'package:flutter/material.dart';
import 'avatar_controller.dart';
class AvatarScreen extends StatelessWidget {
const AvatarScreen({super.key, required this.controller});
final AvatarController controller;
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListenableBuilder(
listenable: controller,
builder: (context, _) {
return Column(
children: [
Text(controller.photo?.name ?? 'No photo selected'),
if (controller.error != null) Text(controller.error!),
TextButton(
onPressed: () => controller.choose(useCamera: false),
child: const Text('Gallery'),
),
TextButton(
onPressed: () => controller.choose(useCamera: true),
child: const Text('Camera'),
),
],
);
},
),
);
}
}// test/avatar_screen_test.dart
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_demo/avatar_controller.dart';
import 'package:photo_demo/avatar_screen.dart';
import 'fake_photo_source.dart';
void main() {
testWidgets('shows the file name after picking', (tester) async {
final controller = AvatarController(
FakePhotoSource(gallery: XFile('/tmp/cat.jpg')),
);
await tester.pumpWidget(
MaterialApp(home: AvatarScreen(controller: controller)),
);
expect(find.text('No photo selected'), findsOneWidget);
await tester.tap(find.text('Gallery'));
await tester.pump();
expect(find.text('cat.jpg'), findsOneWidget);
});
}Testing camera code
CameraController follows the same rule: do not construct it inside widgets you want to test. Put a wrapper around the parts you use (initialize, takePicture, dispose) and fake the wrapper. The camera package does expose a platform interface that you can replace in tests, but a fake of that interface must implement many methods and tends to break when the plugin is upgraded. A wrapper you own changes only when your app changes.
Things you can verify with a fake camera:
- The screen shows a progress indicator while initialization is pending.
- The screen shows a fallback message when initialization throws a
CameraException. - The shutter button calls
takePictureonce and passes the resulting path onward. disposeis called when the screen is removed.
Verify on real devices
Fakes cannot tell you whether your Info.plist strings exist, whether the Android manifest is correct, or whether the preview is rotated correctly. Run the checklist below on at least one Android phone and one iPhone before each release.
| Check | How to run it | What to look for |
|---|---|---|
| First-run permission prompt | Uninstall the app, reinstall, open the camera screen | The system dialog appears and your usage text is readable |
| Permission denied | Tap "Don't allow", or revoke in system settings | The app shows a fallback, not a crash or a blank screen |
| Denied then re-granted | Enable the permission in Settings, return to the app | The camera starts without restarting the app |
| Background and resume | Press Home during preview, then return | The preview comes back, with no frozen frame or error |
| Rotation | Rotate the device on the preview and on the result | The preview and the saved photo have the correct orientation |
| Cancelled pick | Open the picker and back out | The app keeps its old state |
| Large images | Pick a 12-megapixel photo with and without `maxWidth` | No out-of-memory error, and the upload size looks right |
| Android activity restart | Turn on "Don't keep activities" in Developer options, take a photo with `ImageSource.camera`, return to the app | Your `retrieveLostData` handling restores the result |
You can reset and change permissions from a terminal instead of tapping through settings. Replace the package and bundle IDs with your own.
# Android: revoke and grant the camera permission
adb shell pm revoke com.example.photo_demo android.permission.CAMERA
adb shell pm grant com.example.photo_demo android.permission.CAMERA
# iOS simulator: reset or grant camera access
xcrun simctl privacy booted reset camera com.example.photo_demo
xcrun simctl privacy booted grant camera com.example.photo_demoThe iOS simulator has no camera, so a CameraController there cannot show a real preview. Use a physical iPhone for anything involving live capture. The Android emulator provides a virtual camera, which is enough for a smoke test but does not behave like real hardware for focus, zoom, or flash.
Integration tests
The integration_test package runs your app on a device and can tap through your UI. It cannot dismiss a native permission dialog by itself. Pre-grant the permission with adb or simctl before the run, or use the fake PhotoSource in the test so the picker never opens. Both approaches give repeatable results. Reserve the real dialog for your manual checklist.
Exercise
A teammate's widget test calls ImagePicker().pickImage(source: ImageSource.gallery) through the widget under test and fails with a MissingPluginException. What change fixes the test, and why?
Show answer
Hide the plugin behind an interface such as PhotoSource, give the widget or its controller that interface, and pass a fake in the test. The test runs on the host machine, where no native picker exists to answer the platform channel, so the real call fails. A fake returns a prepared XFile without any platform code.
Exercise
Name two behaviors that a fake PhotoSource cannot verify, and say how you would check each one.
Show answer
Examples: whether the user sees the permission prompt with your usage text, and whether the app recovers lost data after Android destroys the activity. Check the first by reinstalling the app on a real device and opening the camera screen. Check the second by enabling "Don't keep activities" in Developer options, taking a photo, and returning to the app. Other valid answers include preview orientation, background and resume behavior, and memory use with large photos.