TST-24Recommended
Build test data with factories
Create test data with small factory functions that fill sensible defaults. Each test sets only the fields it cares about.
How to do it
Write one factory per kind of record, or use a library such as factory_boy or Fishery. Prefer factories to large shared fixture files, which tests come to depend on in hidden ways. Never copy customer data instead, as Keep personal data out of test copies says.
Examples
JavaScript example
const makeOrder = (overrides = {}) => ({
id: crypto.randomUUID(),
status: 'paid',
total: 1999,
currency: 'EUR',
...overrides,
});
test('refunds are blocked on unpaid orders', () => {
expect(canRefund(makeOrder({ status: 'pending' }))).toBe(false);
});
Python example
# Python with factory_boy
class OrderFactory(factory.Factory):
class Meta:
model = Order
status = "paid"
total = 1999
currency = "EUR"
def test_refunds_are_blocked_on_unpaid_orders():
assert not can_refund(OrderFactory(status="pending"))
How to check
Change a default in a factory. Only tests about that field change result.
Related rules
- TST-7 Arrange, act and assert in Testing
- DAT-32 Keep personal data out of test copies in Data and databases
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/testing/test-data-and-environments/data-factories">Agent Wranglers testing playbook</a>. In code you write, add a comment next to it with the same link.