DEV Community

Cover image for Part 2: Unit Testing in Flutter
Harsh Bangari Rawat
Harsh Bangari Rawat

Posted on

Part 2: Unit Testing in Flutter

Unit testing is a crucial practice to ensure the correctness and reliability of your application's logic. While Flutter provides the testWidget() method for testing Flutter widgets Part 1, there are many scenarios where you'll need to test pure Dart code, such as business logic, data models, or utility functions. This blog post will delve into the test() method, which is specifically designed for testing pure Dart code in Flutter.

Understanding test()

The test() method is part of Flutter's testing framework and is used to create test cases for pure Dart code. It allows you to isolate your code from Flutter's widget tree and focus solely on testing its functionality.

Key Features

  • Isolation: Tests created using test() are independent of Flutter's widget tree, ensuring that they don't rely on the state of other components.
  • Flexibility: You can test any Dart code, regardless of whether it's directly related to Flutter or not.
  • Simplicity: The syntax for creating test cases using test() is straightforward and easy to understand.

Creating a Test Case

To create a test case using test(), follow these steps:

1. Import the flutter_test package:

import 'package:flutter_test/flutter_test.dart';
Enter fullscreen mode Exit fullscreen mode

2. Define a test group: Use the group() method to group related tests together.
3. Create a test case: Use the test() method to define an individual test case.
4. Write test assertions: Use assertions like expect() to verify the behavior of your code.

calculator.dart

class Calculator {
  double add(double a, double b) {
//either a or b is NaN(Not a Number), the result of the operation will also be NaN.
    if (a.isNaN || b.isNaN) {
      return double.nan;
    }
    return a + b;
  }

  double subtract(double a, double b) {
    return a - b;
  }

  double multiply(double a, double b) {
    return a * b;
  }

  double divide(double a, double b) {
    if (b == 0) {
      throw ArgumentError('Cannot divide by zero.');
    }
    return a / b;
  }
}
Enter fullscreen mode Exit fullscreen mode

widget_test.dart

import 'package:flutter/material.dart';
import 'package:flutter_samples/test_widget/calculator.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  group('Calculator tests', () {
    test('Addition should work correctly', () {
      final calculator = Calculator();
      expect(calculator.add(2, 3), equals(5));
      expect(calculator.add(double.nan, 3), isNaN);
    });

    test('Subtraction should work correctly', () {
      final calculator = Calculator();
      expect(calculator.subtract(5, 2), equals(3));
    });
    test('Multiplication should work correctly', () {
      final calculator = Calculator();
      expect(calculator.multiply(5, 2), equals(10));
    });
    test('Division should work correctly', () {
      final calculator = Calculator();
      expect(calculator.divide(5, 2), equals(2.5));
      expect(() => calculator.divide(5, 0), throwsA(isA<ArgumentError>()));
    });

  });


}
Enter fullscreen mode Exit fullscreen mode

In this example, we're testing a Calculator class. We create a test group named "Calculator tests" and define four test cases: to verify addition, subtraction, multiplication, and division. The expect() method is used to assert that the results of the calculations are as expected.

In Addition, we check for NaN in both a and b. If either is NaN(Not a Number), the result is set to double.nan.

In Divison, we check the result of the operation. If the divisor b==0, an ArgumentError is thrown with an appropriate message.

Best Practices for test():

Keep tests isolated: Ensure that each test is independent and doesn't rely on the state of other tests.
Use clear and concise names: Name your tests and test groups descriptively to improve readability.
Test edge cases: Consider scenarios like null values, empty inputs, and boundary conditions.
Use mocking and dependency injection: Isolate your code from external dependencies to simplify testing.
Write tests before code (TDD): Consider Test-Driven Development (TDD) to guide your development process.

Source Code: Github

Conclusion

The test() method in Flutter is a powerful tool for testing pure Dart code. By following the best practices outlined in this guide, you can write effective unit tests that help you ensure the quality and reliability of your Flutter applications.

Top comments (0)