Software Testing Engineering / UNIT TEST DESIGN & AUTOMATION / TST-007

Money Unit Tests

Explore concept graph

Materi

Problem: kalkulasi fee tampak benar untuk input normal, tetapi salah ketika nominal nol, negatif, maksimum, atau tepat di ambang pembulatan. Bagaimana membuat regression tests yang benar-benar mendeteksi perubahan aturan fee?

Langkah pertama: buat satu test JUnit Jupiter dengan tiga tahap Arrange → Act → Assert, yang membandingkan hasil publik calculateFee dengan BigDecimal yang tepat.

Peta konsep statis. Ikuti alur teks dari atas ke bawah.
                  Java 21 + BigDecimal
                           |
         +-----------------+-----------------+
         |                                   |
    fee policy                           input contract
    rate = 1.5%                        IDR 0 decimals
    max = 1,000,000                    USD 2 decimals
         |                                   |
         +-----------------+-----------------+
                           |
                   FeeCalculator
                           |
                      JUnit Jupiter
             Arrange -> Act -> Assert
             @Test  /  @BeforeEach
                           |
               [normal, zero, negative,
                maximum, rounding, currency]
                           |
                     Maven Surefire
                       clean verify
                           |
                tests > 0, failures = 0

Kontrak FeeCalculator untuk lab

Ini adalah kebijakan contoh untuk latihan, bukan tarif perusahaan finansial atau FX conversion. Tarif fee kedua mata uang adalah 1,5%, jumlah principal valid dari 0 sampai 1.000.000 unit mata uang, dan rounding fee memakai HALF_UP.

Input Expected behavior
IDR 10.000 fee IDR 150
USD 100.00 fee USD 1.50
IDR 0 / USD 0.00 fee nol dengan scale masing-masing
IDR -1 / USD -0.01 IllegalArgumentException
IDR 1.000.000 / USD 1,000,000.00 fee valid 15.000 / 15,000.00
Nilai di atas maksimum IllegalArgumentException
IDR 33 dan 34 fee 0 dan 1
USD 0.33 dan 0.34 fee 0.00 dan 0.01
IDR 1.50 / USD 1.001 ArithmeticException karena principal scale invalid
Currency EUR IllegalArgumentException; tidak ada konversi

Perhitungan memakai new BigDecimal("0.015"), bukan double. RoundingMode.UNNECESSARY memvalidasi jumlah desimal input principal; RoundingMode.HALF_UP hanya digunakan saat membulatkan fee yang dihitung. BigDecimal.compareTo digunakan untuk batas numerik, sedangkan assertEquals atas hasil fee juga memeriksa scale output yang menjadi bagian kontrak.

Konsep 1 / 3

Write a JUnit Jupiter unit test using Arrange–Act–Assert, @Test and @BeforeEach without Spring context.

Fee rules should be verified in milliseconds with deterministic inputs instead of starting a database or HTTP server for every case.

Mulai dari sini

Create a descriptive @Test named normalIdrAmountReturnsFee and prepare a new FeeCalculator.

Intuisi utama

Arrange the money input and calculator, Act once by computing the fee, Assert the returned BigDecimal or expected exception; @BeforeEach prepares fresh test state.

JUnit Jupiter discovers @Test methods through the Jupiter engine; @BeforeEach runs before each test. In this sandbox, a plain Java FeeCalculator has no framework dependency or IO. Use descriptive test names and assert visible behavior, not the implementation's private branch structure. Tests are executed via Maven Surefire using junit-jupiter test scope. The lab's example fee policy is explicitly invented for education, not a bank product fee schedule: 1.5% rate, IDR scale 0, USD scale 2, maximum principal 1,000,000 currency units.

Contoh bertahap

A fee for IDR 10000 must be exactly IDR 150, and a test should independently report that result.

  1. Arrange a FeeCalculator instance and new BigDecimal("10000") with currency code IDR.

    Mengapa: String decimal input avoids surprises from binary double constructors.

    Hasil yang diharapkan: Test inputs are exact integers and a declared currency.

  2. Act with calculator.calculateFee(amount, "IDR").

    Mengapa: The public method is the observable business contract.

    Hasil yang diharapkan: A BigDecimal result is produced without Spring application context.

  3. Assert a BigDecimal result of 150, and rerun through Maven.

    Mengapa: The test should prove the calculation, not whether a specific internal multiplication is used.

    Hasil yang diharapkan: One descriptive Jupiter @Test passes under Maven Surefire.

Konsep 2 / 3

Check zero/negative amounts, exactly-at-cap and above-cap values, and expected exceptions as separate observable outcomes.

An apparently correct normal-case test can miss invalid fees for negative payments or unexpected overflow in maximum-sized transfers.

Mulai dari sini

List expected outcomes for 0, -1, 1000000 and 1000001 before writing test code.

Intuisi utama

Partition inputs by behavior: zero is allowed, negative is rejected, in-range values calculate, exact maximum is valid, and above maximum is rejected.

The lab contract chooses 1,000,000 units as maximum input principal per currency. It accepts zero as a zero fee but rejects negative principal, amounts above maximum, unsupported currency codes and non-representable currency scales. Both IDR and USD share the same numerical rate, not an exchange rate. JUnit assertThrows checks expected IllegalArgumentException and ArithmeticException, while assertEquals checks valid boundary outputs. Test the maximum itself and a value above it separately; they are not equivalent cases. Null is rejected by explicit validation.

Contoh bertahap

Calculator returns correct fee for 10000 IDR but must also protect its input boundaries.

  1. Test IDR zero and USD zero separately.

    Mengapa: Different currency scales must produce 0 versus 0.00.

    Hasil yang diharapkan: Both return a zero-valued BigDecimal with the declared currency scale.

  2. Test IDR -1 and USD -0.01 with assertThrows.

    Mengapa: A failed validation should be an expected observable exception, not an uncaught test failure.

    Hasil yang diharapkan: Both invalid amounts reject before a fee is calculated.

  3. Test principal 1000000 and 1000001 in IDR.

    Mengapa: The maximum boundary has two distinct expected branches.

    Hasil yang diharapkan: At-limit returns IDR 15000, above-limit raises IllegalArgumentException.

Konsep 3 / 3

Test rounding near thresholds and enforce IDR/USD minor-unit precision with a reproducible Maven run.

Using binary floating-point or inconsistent rounding can change financial amounts silently, and the passing IDE button does not prove build reproducibility.

Mulai dari sini

Calculate the exact product of USD 0.34 and 0.015 before applying the two-decimal rounding rule.

Intuisi utama

BigDecimal carries exact decimal value and scale; the fee is exact principal × 0.015, then HALF_UP to 0 IDR decimals or 2 USD decimals.

For the lab, IDR 33 × 0.015 = 0.495 rounds to IDR 0; IDR 34 × 0.015 = 0.510 rounds to IDR 1. USD 0.33 × 0.015 = 0.00495 rounds to USD 0.00; USD 0.34 yields 0.00510 and rounds to USD 0.01. Rounding happens once after exact multiplication. Reject IDR 1.50 and USD 1.001 rather than silently modifying invalid principal precision. BigDecimal.compareTo can consider 2.0 and 2.00 numerically equal while equals considers scale, so use exact expected scale when that is part of the public output contract. Maven clean verify runs independent Jupiter unit tests without Spring context; a V3 single-file Java fixture cannot prove Maven/JUnit dependencies, so that integration evidence is in a separate CI gate.

Contoh bertahap

A cent-scale fee just below a rounding threshold incorrectly returns one cent.

  1. Compute fee for USD 0.33 and 0.34 with decimal-string inputs.

    Mengapa: These amounts straddle a HALF_UP rounding threshold.

    Hasil yang diharapkan: Expected USD fees are 0.00 and 0.01, respectively.

  2. Compare IDR 33 and 34 fees and reject malformed principal scale.

    Mengapa: IDR has no minor unit, while USD has two decimals.

    Hasil yang diharapkan: IDR 0 versus 1 at the threshold; IDR 1.50 and USD 1.001 are invalid.

  3. Run mvn -B -ntp -f labs/TST-007/pom.xml clean verify.

    Mengapa: A real Maven run validates Jupiter discovery and the pure Java money contract.

    Hasil yang diharapkan: Surefire reports all tests passed without a Spring context.

Referensi resmi

Sumber

Cross-domain connections

Curated relationships for this unit at G1. Proposed edges are suggestions, not prerequisites.

Concept connectionsG1 · 1 visible concepts · 1 curated links
100%

Dashed = proposed relationship; solid = reviewed connection. Only reviewed prerequisites constrain a learning path. Keyboard and text links remain available.