Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing in Flutter passing BuildContext

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.

like image 729
Nicolas Avatar asked May 23 '19 14:05

Nicolas


People also ask

What does BuildContext mean in Flutter?

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.

What is of () in Flutter?

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.


1 Answers

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();       },     ),   ); }); 
like image 147
jamesdlin Avatar answered Oct 05 '22 03:10

jamesdlin