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

By | September 24, 2018

Lets see how we can test Flutter Apps.

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

 

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 *