How to do Unit Test of functions and Widgets in Flutter?

By | December 29, 2018

Lets see how we can test Flutter Apps.

It would be easy if we continue from the previous example…

 

Main.dart

This is my main file that i am going to test

main.dart

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  int findSquare(int number) {
    return number * number;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Unit Test Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  testFunction(){
    return 100;
  }

  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

We are going to test if the widgets have properly launched and the functions findSquare and testFunction are properly working.

Start unit Testing

We will create a test file named ‘widget_test.dart’ inside the ‘test’ folder.

To test Widgets, we will use the ‘testWidgets’ function.

Lets see how it will look like…

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import '../../flutter_demo1/lib/Pages/init_page.dart';
import '../../flutter_demo1/lib/Pages/home.dart';

void main() {
  testWidgets('Counter increments smoke test', (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.pumpWidget(new MyApp());

    // Verify that our counter starts at 0.
    expect(find.text('0'), findsOneWidget); // this ensures that there is a widget
    expect(find.text('1'), findsNothing); // this ensures that there is no widget

    // Tap the '+' icon and trigger a frame.
    await tester.tap(find.byIcon(Icons.add));
    await tester.pump();

    // Verify that our counter has incremented.
    expect(find.text('0'), findsNothing); 
    expect(find.text('1'), findsOneWidget);
  });

  test('my simple unit test', () {
    var answer = 42;
    expect(answer, 42);
  });

  test('Testing Square function in  MyApp page...', (){
    expect(new MyApp().findSquare(), 10);
  });

  test('Testing function in HomePage...', (){
    expect(new MyHomePage().testFunction(), 50);
  });

  test('Testing State test function...', (){
    expect(new MyHomePage().createState().testStateFunction(), 60);
  });
  
}

The test function in MyHomePage will look like this

    int testStateFunction(){
        return 60;
    }

Run Tests

To run test we have to run ‘flutter test test/widget_test.dart’ in the terminal.
To run all the tests, run ‘flutter test’.

If you are using VSCode, then you can see the ‘Run‘ link above each test case. You can simple click on it to run. You can see a sample screenshot below.

You should see “All tests passed!” when all tests are successful.

Leave a Reply

Your email address will not be published. Required fields are marked *