How do you test code that uses encapsulation?

This article explains how to effectively test code that utilizes encapsulation principles in Java. Encapsulation is a fundamental concept in object-oriented programming that helps to hide the internal state and behavior of an object, exposing only what is necessary through public methods.
encapsulation, Java, testing, object-oriented programming, unit testing
// Example of encapsulation in a Java class public class Account { private double balance; public Account(double initialBalance) { balance = initialBalance; } public void deposit(double amount) { if (amount > 0) { balance += amount; } } public void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; } } public double getBalance() { return balance; } } // Testing the Account class public class AccountTest { private Account account; @Before public void setUp() { account = new Account(100.0); // Initialize with balance of 100 } @Test public void testDeposit() { account.deposit(50.0); assertEquals(150.0, account.getBalance(), 0.001); } @Test public void testWithdraw() { account.withdraw(30.0); assertEquals(70.0, account.getBalance(), 0.001); } @Test public void testWithdrawTooMuch() { account.withdraw(150.0); assertEquals(100.0, account.getBalance(), 0.001); } }

encapsulation Java testing object-oriented programming unit testing