Test data builders
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
create test objects without copy-paste.
Planned topics
- Long constructors repeated in every test hide what matters.
- A builder has sensible defaults; the test overrides only the relevant fields:
aProduct().withStock(0).build(). - An object mother is a class of named factories:
Products.outOfStock(). - Defaults must be valid so tests start from a good state.
- Keep builders in test code, not production.
Draft outline details
Demonstration
class ProductBuilder {
private String name = "Pen"; private int stock = 10; private BigDecimal price = new BigDecimal("2.50");
static ProductBuilder aProduct() { return new ProductBuilder(); }
ProductBuilder withStock(int s) { this.stock = s; return this; }
Product build() { return new Product(name, price, stock); }
}Check your understanding
What should a builder's defaults be?
Show answer
Valid, so tests set only what they care about.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.