I am beginning to learn automated tests with flutter, since i want to use the flutter_driver to take a screenshot on a failed expect i created a class that does a try of the test and catches TestFailure by doing a screenshot and rethrowing the failure.
I am using the default flutter app (the one with the counter and the button to increase it).
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
import 'dart:io';
class CustomTest {
Function testDetails;
String testName;
FlutterDriver? driverr;
CustomTest(this.testDetails, this.testName, this.driverr);
void runTest() {
test(testName, () async {
try {
await testDetails();
} on TestFailure catch (_) {
await takeScreenshot();
rethrow;
}
});
}
Future<File> takeScreenshot() async {
final List<int> pixels = await driverr!.screenshot();
final File file = File('test_driver/results/${testName}_failure.png');
await file.writeAsBytes(pixels);
return file;
}
}
void main() {
group('Counter App', () {
FlutterDriver? driver;
setUpAll(() async {
driver = await FlutterDriver.connect();
});
tearDownAll(() async {
driver?.close();
});
final counterTextFinder = find.byValueKey('counter');
final buttonFinder = find.byValueKey('increment');
CustomTest test1 = CustomTest(() async {
expect(await driver?.getText(counterTextFinder), "1");
}, "Starts at 0", driver);
test1.runTest();
CustomTest test2 = CustomTest(() async {
await driver?.tap(buttonFinder);
expect(await driver?.getText(counterTextFinder), "2");
}, "Increments the counter", driver);
test2.runTest();
});
}
However, when i run my tests (which i modified to fail to test the screenshot) i get a null exception because the driver is null.
I tried extracting the code from the takeScreenshot() method and putting it on the test description itself, there it runs without issues.