Site Tools


swe:unit-test

Table of Contents

Unit test

Unit test is a test that verifies a single function or method in isolation from its dependencies. Dependencies are replaced with fakes (stubs, mocks) that return controlled values so the test is fast and deterministic.

Integration tests and end-to-end tests verify the whole system but run slowly and are brittle. Unit tests alone cannot catch bugs that only appear when components interact, for example when one function passes data in a format the downstream component does not expect.

Unit tests sit at the bottom of the test pyramid: cheap to write and run, so you have many of them. They isolate the code under test, making tests fast (microseconds) and deterministic rather than flaky. Unit tests and integration tests complement each other.

Dependencies are injected and replaced with fakes, so the test controls all inputs and outputs.

# Unit test with mocked dependency
class PaymentProcessor:
    def __init__(self, gateway):
        self.gateway = gateway  # injected, not hard-coded
 
    def charge(self, user_id, amount):
        return self.gateway.authorize(user_id, amount)
 
# Mock replaces the real gateway
class MockGateway:
    def authorize(self, user_id, amount):
        return {'status': 'approved'}
 
def test_charge_succeeds():
    processor = PaymentProcessor(MockGateway())
    result = processor.charge('user123', 100)
    assert result['status'] == 'approved'
swe/unit-test.md · Last modified: by 127.0.0.1