0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · Pelajaran

Menulis Pengujian Terlebih Dahulu

Berlatih menulis pengujian yang gagal untuk mendefinisikan perilaku yang diinginkan sebelum menerapkan kode produksi apa pun.

Menulis Pengujian Terlebih Dahulu adalah pelajaran Testing Mastery: JUnit, Mockito & Integration Tests gratis di CoddyKit. Ini adalah pelajaran 2 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Testing Mastery: JUnit, Mockito & Integration Tests, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Testing Mastery: JUnit, Mockito & Integration Tests mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

TDD's 'Red' Phase

Welcome to the core of Test-Driven Development (TDD)! In this lesson, we'll dive into the crucial first step: writing a failing test first.

This is often called the 'Red' phase of the TDD cycle, because when you run your tests, you expect to see a 'red bar' indicating a failure.

Why Test First?

It might feel counter-intuitive to write a test for code that doesn't exist yet, or isn't fully implemented. But this approach offers great benefits:

  • Clarity: It forces you to think about what the code should *do* before you think about *how* to do it.
  • Proof of Failure: It proves your test works correctly by showing it can fail. If it passes without any code, your test might be faulty!
  • Focus: It gives you a clear, immediate goal: make this one test pass.

Tests as Specifications

Think of your failing test as a precise specification or a mini-requirement. It describes a specific behavior your future code must exhibit.

  • It defines the input.
  • It defines the expected output or outcome.
  • It's concrete and executable.

This helps prevent misunderstandings and ensures your code delivers exactly what's needed for that specific scenario.

Scenario: Simple Calculator

Let's practice by building a simple Calculator class. For our first piece of functionality, we want it to be able to add two numbers.

Our goal is to write a test for an add method that will fail before we even write the correct implementation of add.

Designing the Failing Test

Before writing code, let's think:

  • What input? We'll add 2 and 3.
  • What output? We expect the result to be 5.
  • What method? A method called add on a Calculator object.

We'll write a test that calls calculator.add(2, 3) and asserts that the result is 5.

Code Demo: The Failing Test

Here's a simulated example of writing a test first. Notice the Calculator's add method is intentionally incorrect (it returns 0). This makes our 'test' fail, demonstrating the 'Red' phase.

Run this code to see the simulated failure!

public class Main {
    public static void main(String[] args) {
        System.out.println("Running a simulated test...");
        Calculator calculator = new Calculator();

        // Our test scenario: 2 + 3 should be 5
        int expected = 5;
        int actual = calculator.add(2, 3);

        if (expected == actual) {
            System.out.println("Test PASSED: 2 + 3 = " + actual);
        } else {
            System.out.println("Test FAILED: Expected " + expected + " but got " + actual);
            System.out.println("This is our 'Red' phase!");
        }
    }
}

// The production code (intentionally incorrect for 'Red' phase)
class Calculator {
    public int add(int a, int b) {
        return 0; // Wrong implementation to make the test fail
    }
}

Analyzing the 'Red'

After running the previous code, you saw a 'Test FAILED' message. This is exactly what we wanted!

  • Expected: 5
  • Actual: 0

This failure confirms two things: our test is correctly written, and the production code (the add method) does not yet meet the specified behavior.

The 'Minimum Code' Mindset

Once you have a failing test, the next step in TDD (the 'Green' phase) is to write the *simplest possible code* to make that test pass.

  • Don't over-engineer.
  • Don't add extra features.
  • Just focus on satisfying the current failing test.

This keeps your code clean and focused, building functionality incrementally.

Advantages of Test-First

Embracing the 'Red' phase of TDD leads to:

  • Better Design: Tests guide you towards more modular and testable code.
  • Increased Confidence: Each passing test gives you confidence in your code's correctness.
  • Reduced Bugs: Catch issues early, before they become complex problems.
  • Living Documentation: Your tests serve as up-to-date examples of how your code should be used.

Quick Check on TDD Red

Let's test your understanding of the 'Red' phase in Test-Driven Development.

Recap: The 'Red' Phase

You've explored the crucial first step of TDD: writing a failing test.

  • The 'Red' phase means writing a test that fails.
  • This test acts as a clear specification for new functionality.
  • Seeing the test fail confirms its validity and that the code isn't yet correct.
  • This methodical approach leads to clearer requirements and more robust code.

Next, we'll learn how to make that failing test pass – the 'Green' phase!

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Menulis Pengujian Terlebih Dahulu” gratis?

Ya — teks lengkap “Menulis Pengujian Terlebih Dahulu” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Testing Mastery: JUnit, Mockito & Integration Tests, upgrade ke CoddyKit PRO. Kursus Testing Mastery: JUnit, Mockito & Integration Tests mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Menulis Pengujian Terlebih Dahulu”?

Berlatih menulis pengujian yang gagal untuk mendefinisikan perilaku yang diinginkan sebelum menerapkan kode produksi apa pun. Kamu berlatih Testing Mastery: JUnit, Mockito & Integration Tests dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Testing Mastery: JUnit, Mockito & Integration Tests?

Tidak diperlukan pengalaman sebelumnya. Testing Mastery: JUnit, Mockito & Integration Tests di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 2 dari 4.

Berapa lama pelajaran “Menulis Pengujian Terlebih Dahulu” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Testing Mastery: JUnit, Mockito & Integration Tests ini?

Ya. Setiap pelajaran Testing Mastery: JUnit, Mockito & Integration Tests menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Pengantar Siklus TDD
  2. Menulis Pengujian Terlebih Dahulu
  3. Pemfaktoran Ulang untuk Kemudahan Pengujian
  4. Tiga Hukum TDD
← Kembali ke Testing Mastery: JUnit, Mockito & Integration Tests