0
0
Fluttermobile~15 mins

Unit testing in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Calculator Logic Test
This screen is for testing the logic of a simple calculator function that adds two numbers. It does not have a UI but focuses on unit testing the addition function.
Target UI
No UI - This is a unit test file for calculator logic.
Create a function add(int a, int b) that returns the sum of a and b.
Write a unit test to check if add(2, 3) returns 5.
Write a unit test to check if add(-1, 1) returns 0.
Use Flutter's test package for writing tests.
Starter Code
Flutter
int add(int a, int b) {
  // TODO: Implement addition
  return 0;
}

// TODO: Write unit tests here
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter_test/flutter_test.dart';

int add(int a, int b) {
  return a + b;
}

void main() {
  test('add(2, 3) returns 5', () {
    expect(add(2, 3), 5);
  });

  test('add(-1, 1) returns 0', () {
    expect(add(-1, 1), 0);
  });
}

We implemented the add function to simply return the sum of two integers. Then, we wrote two unit tests using Flutter's test package. Each test checks if the add function returns the expected result for given inputs. This helps ensure our addition logic works correctly.

Final Result
Completed Screen
No UI - This is a unit test file.

Tests run in console output:

[✓] add(2, 3) returns 5
[✓] add(-1, 1) returns 0
Run tests using flutter test command in terminal.
See test results pass or fail in console.
Stretch Goal
Add a unit test for add(0, 0) returning 0.
💡 Hint
Write a new test() block similar to existing ones checking add(0, 0) == 0.