Learn
← Previous Next →

Hari 26: Testing di Dart & Flutter

60 min Last updated 09 Apr 2026

Unit Testing di Dart

// test/kalkulator_test.dart
import "package:test/test.dart";
import "kalkulator.dart";

void main() {
  group("Kalkulator", () {
    late Kalkulator kalk;

    setUp(() => kalk = Kalkulator());

    test("tambah dua angka positif", () {
      expect(kalk.tambah(2, 3), equals(5));
    });

    test("bagi dengan nol throw Exception", () {
      expect(() => kalk.bagi(10, 0), throwsException);
    });

    test("hitung diskon", () {
      expect(kalk.diskon(100000, 20), equals(80000));
    });
  });
}

Widget Testing

// test/counter_test.dart
import "package:flutter_test/flutter_test.dart";
import "package:myapp/counter.dart";

void main() {
  testWidgets("Counter increment test", (tester) async {
    await tester.pumpWidget(MaterialApp(home: CounterPage()));

    expect(find.text("0"), findsOneWidget);
    await tester.tap(find.byIcon(Icons.add));
    await tester.pump();
    expect(find.text("1"), findsOneWidget);
  });
}

💡 Notice: Testing yang baik mencakup: happy path, edge cases, dan error conditions.

Assignment

Tulis 5+ unit test untuk class Kalkulator termasuk test exception.

Expected output:

✓ tambah positif
✓ kurang negatif
✓ kali nol
✓ bagi normal
✓ diskon 20%
✓ diskon 0%
✓ diskon 100%
✓ bagi nol throw error
--- Hasil: 8 passed, 0 failed ---
Dart main.dart
Solution
Output