Юрий Терец
Юрий Терец

Reputation: 11

Flutter Unit test

Good day! I have a flutter test project, I want to write a unit test to it. But I can't figure out how to do it. Tap on the screen changes the background color. I want some tips and if possible examples, here is my code:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Color randomColor;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          randomColor = Color((Random().nextDouble() * 0xFFFFFF).toInt())
              .withOpacity(1.0);
        });
      },
      child: Scaffold(
          backgroundColor: randomColor,
          body: Container(
            child: Center(
              child: Text('Hey, there'),
            ),
          )),
    );
  }
}

Upvotes: 1

Views: 909

Answers (1)

Pritam Mullick
Pritam Mullick

Reputation: 226

Flutter comes built in with a testing package. All we need to import is import 'package:test/test.dart'; in our dart file where we write the test scripts. Also add test package in pubspec.yaml file.

A good resource to start with is the Flutter documentation and follow along, if you're absolutely new to Flutter Testing.

Coming to your question, it is absolutely impossible to test and validate the background color on tap, as it randomly generated but off course you can add a simple unit test for the above dart code, to find and match whether the Text widget is displayed or not. Here goes the test code, for such a scenario.

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

  /// Creating a new Flutter-Widget-test
  testWidgets('Simple Flutter Test Example', (WidgetTester tester) async {
    
    /// Pumping the widget to the screen [build and rendering]
    await tester.pumpWidget(myApp());

    /// Set finders
    var textFinder = find.text('Hey, there');

    /// Set matchers
    expect(textFinder, findsOneWidget);
  });
}

This is more of a Widget Testing in Flutter rather than an Unit Test. For more details on Widget Testing and it's methods, follow documentation on introduction, widget finders, tap and drag events.

Upvotes: 1

Related Questions