Skip to content

emka.web.id

writing knowledge, recording civilization

Menu
  • Home
  • Tutorial
  • Search
Menu

Stub_Gen, Package Flutter untuk Buat Stub Object dengan Cepat

Posted on June 8, 2024

Dunia pengembangan aplikasi mobile semakin dinamis. Flutter, sebagai framework cross-platform populer, terus berkembang dengan fitur-fitur baru seperti sealed class, record, dan deconstructing via pattern matching di Dart 3. Peningkatan ini tentunya membuat pengembangan aplikasi Flutter semakin menarik!

Artikel ini akan membahas stub_gen, sebuah package Dart yang dapat membuat stub secara otomatis untuk objek Dart. Stub sendiri berguna untuk memfasilitasi pembuatan unit test, terutama ketika kita berhadapan dengan class yang besar dan kompleks.

Kenapa Menggunakan Stub?

Stub memiliki beberapa manfaat dalam pengembangan aplikasi, terutama saat:

  • Menulis unit test untuk class besar: Mengisolasi logika class yang kompleks menjadi lebih mudah dengan bantuan stub.
  • Mengembangkan fitur baru tanpa menunggu tim lain: Anda dapat melanjutkan pengembangan fitur baru tanpa terpaku pada progres tim lain, misalnya tim backend server.

Membuat stub secara manual biasanya membutuhkan penetapan nilai awal untuk setiap parameter. Proses ini bisa memakan waktu dan membosankan. Inilah mengapa stub_gen hadir untuk membantu Anda!

Melihat Manfaat stub_gen dengan Contoh

Mari kita lihat contoh kode aplikasi berikut:

class Todo {
  Todo({
    required this.id,
    required this.title,
    required this.isDone,
    required this.deadline,
    required this.completeFraction,
    required this.ownerId,
  });

  final String id;
  final String title;
  final bool isDone;
  final DateTime deadline;
  final double completeFraction;
  final String ownerId;
}

class System {
  static Future<Todo> makeDone({required String todoId}) async {
    final todo = await Server.fetch(id: todoId);
    todo.isDone = true;
    todo.completeFraction = 1.0;
    await Server.store(todo: updatedTodo);
    return updatedTodo;
  }
}

class Server {
  static final Map<String, Todo> _memory = {};

  static Future<Todo> fetch({required String id}) async {
    return _memory[id]!;
  }

  static Future<void> store({required Todo todo}) async {
    _memory[todo.id] = todo;
  }
}

Untuk mempermudah, contoh ini menggunakan Server in-memory yang tidak terhubung ke jaringan nyata.

Sekarang, kita ingin menguji objek System yang memiliki method makeDone.

Skenario Unit Test:

  • Given: Tugas sedang berlangsung.
  • When: Tugas diselesaikan.
  • Then: Tugas menjadi selesai dengan completeFraction 1.
import 'package:test/test.dart';

void main() {
  group('System', () {
    test('makeDone sets task to done with completeFraction 1.0', () async {
      // Given
      final todo = Todo(
        id: '1',
        title: 'Test Task', // Boilerplate
        isDone: false,
        deadline: DateTime.now().add(const Duration(day: 1)),
        completeFraction: 0.5,
        ownerId: 'owner1', // Boilerplate
      );

      // Store the initial Todo in the server's memory
      Server._memory[todo.id] = todo;

      // When
      final updatedTodo = await System.makeDone(todoId: todo.id);

      // Then
      expect(updatedTodo.isDone, true);
      expect(updatedTodo.completeFraction, 1.0);
    });
  });
}

Meskipun unit test ini sederhana, terdapat beberapa boilerplate seperti title: 'Test Task' dan ownerId: 'owner1'. Saat aplikasi berkembang, boilerplate ini dapat menjadi penghambat penulisan unit test yang bersih.

stub_gen: Solusi untuk Boilerplate

Dengan menggunakan anotasi @StubGen dari stub_gen, kita dapat mengurangi boilerplate pada unit test.

1. Tambahkan Anotasi @StubGen

Tambahkan anotasi @StubGen() ke class yang ingin dibuatkan stub.

@StubGen()
class Todo {
  Todo({
    required this.id,
    required this.title,
    required this.isDone,
    required this.deadline,
    required this.completeFraction,
    required this.ownerId,
  });

  final String id;
  final String title;
  final bool isDone;
  final DateTime deadline;
  final double completeFraction;
  final String ownerId;
}

sadsad

Lanjutan: Meningkatkan Kualitas Unit Test dengan stub_gen di Flutter

2. Generate Stub Code

Setelah menambahkan anotasi @StubGen, jalankan perintah build_runner build untuk menghasilkan stub code.

3. Gunakan Stub di Unit Test

Sekarang, Anda dapat menggunakan stub di unit test Anda.

import 'package:test/test.dart';

void main() {
  group('System', () {
    test('makeDone sets task to done with completeFraction 1.0', () async {
      // Given
      // NOTE: Anda tidak perlu menetapkan nilai persis seperti pada boilerplate.
      final todo = TodoStub.stub(
        isDone: false,
        deadline: DateTime.now().add(const Duration(day: 1)),
        completeFraction: 0.5,
      );

      // Store the initial Todo in the server's memory
      Server._memory[todo.id] = todo;

      // When
      await System.makeDone(todoId: todo.id);

      // Then
      final updatedTodo = Server._memory[todo.id]!;
      expect(updatedTodo.isDone, true);
      expect(updatedTodo.completeFraction, 1.0);
    });
  });
}

Dengan menggunakan stub_gen, unit test Anda menjadi lebih mudah dibaca dan dipahami. Anda tidak perlu lagi terjebak dalam boilerplate yang membosankan.

Kesimpulan

stub_gen dapat membantu Anda menulis unit test yang lebih baik dan lebih cepat dengan mengurangi boilerplate dan meningkatkan keterbacaan kode.

Semoga bermanfaat!

Terbaru

  • How to Install Clean Windows 11 Without Any Bloatware (Step-by-Step Guide)
  • IP Address Rate Limiting is Flawed—Here is the Right Way to Do It
  • Are Fedora 45 Stuck in Its Comfort Zone? A Short Review
  • Hacktober Recap 2026, A Month Full of Dangerous CVE: eMudhra, Gitlab, Brotli, PHP, NodeJS etc
  • 7 Skill Keamanan Jaringan yang Membuat Network Engineer Makin Dibutuhkan
  • How to Spin Up Disposable macOS and Linux VMs on Apple Silicon with TartVM
  • Belajar Cyber Security dari Nol hingga Siap Kerja, Ini Roadmap Lengkapnya
  • Running Windows 11 on Apple Silicon: UTM vs. Parallels Desktop vs. VMware Fusion
  • Testing PikaOS, a Rolling Debian Distribution Special for Gaming and Content Creation
  • Engineering the On-Premises AI Data Center: An In-Depth Technical Review of the HP ZGX Fury AI Station
  • Trying my new Favourite Task Manager, TMOG on Omarchy Linux
  • ASRock Industrial AI Box A395: Is This the Best Compact Strix Halo System for Local AI?
  • Redox OS: A Rust-Based Microkernel Operating System (And How It Differs from Linux)
  • Canonical Is Bringing Back Ubuntu Core Desktop — This Time With a Clearer Plan
  • systemd Officially Adds Support for Rust Components
  • Rocky Linux Creator Builds a Brand-New “Not Linux” Kernel in 11 Days Using AI
  • Building a local AI agent in Workshop on Ubuntu 26.10
  • Omarchy 4.5 RC: 5 New Apps That Actually Look Useful
  • Worth It! Switching from Fedora KDE to Kubuntu
  • I’m Happy Using ‘Herdr’, The Fastest Growing Devtool written in Rust
  • Testing Goose on Omarchy Linux (App & CLI): The Open-Source Solution for Daily Task Automation
  • GNOME Founder Attacks Omarchy Founder as “Lazy, Racist, Ignorant”
  • Why I Stopped Using Plain Command Line Docker and Use Portainer 3.0 To Make My Home Projects Fun Again
  • Why I Switched to a Proper Firewall Box with OPNSense for My Homelab Stuff
  • Fixing Windows Error 0x80070005 Hyper-V Export Access Denied Error the Right Way
  • Fixing Hyper V Export Errors and Building a Better Virtual Machine Setup (error 0x80070002, 0x80070005)
  • Fixing the Dreaded Windows Audio Service Stuck on Stopping Error
  • Windows SIM Error, Unknown error 0xc1420127
  • How I’m Building a Cat Breeding Management App with Python Qt6 + Microsoft Litebox, in 1 Week
  • Why Windows Keeps Nuking Your GPU Drivers (And How to Take Back Control)
  • Canonical: Ubuntu coming soon to Snapdragon X2 Series platforms
  • Finally, wolfSSL adds post-quantum algorithms!
  • How to Run Gemma Embedding Models Using Docker
  • Deploy Nginx Rootful Container with Podman
  • How to Sandboxing Browser on Linux Desktop with Flatpak
  • OpenCode Browse Explained: Automate Any Website WITHOUT APIs
  • Leaked Qwen 4 and GLM 5.5 Post-Training, Beating the 27B Models
  • Do you Agree? Anthropic Secretly Watermarks All Claude’s Text!
  • Some of New Gemini Notebook Update is CRAZY GOOD: Native Mobile Recording
  • Clover 35B A3B Local Test | Diffusion Model Beats Qwen 35B MoE? | Local AI Setup with llama.cpp
  • Lagi rame soal ASN pake mobil dinas buat liburan keluarga, kok bisa dibilang korupsi?
  • Sering lewat di FYP atau X, ini arti istilah seme dan uke yang sering dibahas penggemar anime dan manga
  • Kisah pilu Gilang Dirga pas kehilangan Ace, sempat curhat di podcast Ivan Gunawan soal perjuangan jadi orang tua
  • Aktris muda Noa Nakada meninggal dunia di usia 23 tahun, padahal masih main di Ultraman Teo
  • SpongeBob Bakal Pindah ke RTV November 2026? Warga Lagi Rame Bahas Rumor Ini

©2026 emka.web.id | Design: Newspaperly WordPress Theme