I have a method in a Dart class, which accepts BuildContext
parameter, as follows:
class MyClass { <return_type> myMethodName(BuildContext context, ...) { ... doSomething return something; } }
I want to test that the method works as expected:
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; ... void main() { MyClass sut; setUp(() { sut = MyClass(); }); test('me testing', () { var actual = sut.myMethodName(...); expect(actual, something); }); }
Of course, it won't work, because the method myMethodName
needs a parameter BuildContext
type. This value is available throughout the application itself, but not sure where to get that from in my unit tests.
BuildContext is a locator that is used to track each widget in a tree and locate them and their position in the tree. The BuildContext of each widget is passed to their build method. Remember that the build method returns the widget tree a widget renders. Each BuildContext is unique to a widget.
In the Flutter SDK the . of methods are a kind of service locator function that take the framework BuildContext as an argument and return an internal API related to the named class but created by widgets higher up the widget tree.
One way is to use testWidgets
in combination with a Builder
widget:
testWidgets('me testing', (WidgetTester tester) async { await tester.pumpWidget( Builder( builder: (BuildContext context) { var actual = sut.myMethodName(context, ...); expect(actual, something); // The builder function must return a widget. return Placeholder(); }, ), ); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With