Testing Lombok-based Classes in Java
Lombok simplifies Java by auto-generating boilerplate like getters, setters, and constructors. But how do you **test** classes that use Lombok annotations?
Here's a practical guide to unit testing Lombok-powered classes — and when you might want to go beyond relying on Lombok alone.
✅ Lombok Class Example
Let’s use this simple class as our example:
import lombok.Data;
@Data
public class User {
private String name;
private int age;
}
Lombok generates getName(), setName(), getAge(), setAge(), equals(), hashCode(), and toString().
🔍 Should You Test Getters and Setters?
Generally, you don’t need to test Lombok-generated methods like getters and setters — they’re stable and widely trusted. However, you might want to test:
- Custom logic added manually
- Builder pattern usage
- Correct field population
- Equality and immutability (e.g., for value objects)
📦 Sample JUnit 5 Tests
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class UserTest {
@Test
void testGettersAndSetters() {
User user = new User();
user.setName("Alice");
user.setAge(30);
assertEquals("Alice", user.getName());
assertEquals(30, user.getAge());
}
@Test
void testEqualsAndHashCode() {
User u1 = new User();
u1.setName("Alice");
u1.setAge(30);
User u2 = new User();
u2.setName("Alice");
u2.setAge(30);
assertEquals(u1, u2);
assertEquals(u1.hashCode(), u2.hashCode());
}
@Test
void testToString() {
User user = new User();
user.setName("Bob");
user.setAge(25);
String toString = user.toString();
assertTrue(toString.contains("Bob"));
assertTrue(toString.contains("25"));
}
}
Note: You’re not testing Lombok itself — you’re testing that your class behaves as expected with data populated.
🚀 Testing @Builder Classes
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class Product {
private String name;
private double price;
}
JUnit test for @Builder:
@Test
void testBuilder() {
Product p = Product.builder()
.name("MacBook")
.price(1999.99)
.build();
assertEquals("MacBook", p.getName());
assertEquals(1999.99, p.getPrice());
}
📌 Best Practices
- 📦 Don’t test auto-generated code unless it’s part of complex logic.
- 🔍 Focus on testing behavior, not Lombok.
- 🛠 Use IDEs or decompiled classes to inspect generated code if needed.
- ✅ For teams: document that Lombok is used so others understand what's hidden.
📚 Conclusion
Lombok reduces code clutter — and when used wisely, you don’t need to test the annotations themselves. Focus your tests on functionality and ensure the behavior is correct based on how your classes are used.
Want to see how Lombok compares with record types in Java 14+? Stay tuned!
Comments
Post a Comment