TST-4Recommended
Test behaviour through the public interface
A unit test calls a function or class the way callers do, and checks what it returns or changes.
How to do it
Test through the public function, the public methods or the HTTP interface. Mock only things you do not own, such as a payment provider, never your own classes. Name each test after the behaviour, not the method. A test should survive any refactoring that keeps the behaviour the same.
Examples
JavaScript example
// Bad: tied to a private helper
test('calls _roundCents', () => { /* spies on internals */ });
// Good: tied to behaviour, with money in whole cents
test('a 10% discount on 19.99 gives 17.99', () => {
expect(applyDiscount(1999, 10)).toBe(1799);
});
Python example
# pytest: named after the behaviour, calls only the public function
def test_a_10_percent_discount_on_19_99_gives_17_99():
assert apply_discount(1999, 10) == 1799
How to check
Refactor the inside of a function without changing its results. No test needs to change. No test calls a private method, for example through reflection, @ts-expect-error or a Python _private name.
Related rules
- ENG-5 Unit test every branch and calculation in Engineering
- ARC-39 Keep internals private in Clean code and architecture
- AIF-56 Test agents by the end state in AI features
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/unit-tests/unit-behaviour">Agent Wranglers testing playbook</a>. In code you write, add a comment next to it with the same link.