Skip to content

Unit Tests ​

Start with the smallest function or service that owns the behavior. Give it explicit inputs and assert its result or error. Services with constructor dependencies can use fakes when those dependencies expose a suitable contract.

Command ​

From the Project root, run the service tests already added in Your First Route:

bash
go test ./internal/users -run 'TestService(FindsUser|RejectsEmptyID)$'

Expected result: the users package reports ok for the successful lookup and rejected empty ID. Run go test ./... after the focused check to catch effects on other packages.

Service Tests ​

The First Route service tests call NewService and Find directly. Keep that complete example in the tutorial. Add cases when the service gains a new rule, such as distinguishing a missing record from a dependency failure. Assert domain errors with errors.Is when the error identity is part of the contract.

The service from Save and List Photos uses a concrete PhotoRepo. Test their persistence boundary together with the temporary SQLite service test. That test can construct the service directly while still exercising a real database.

For pure input rules, HTTP Tests also shows a direct test of password preservation. The registered-route table separately verifies HTTP translation and middleware.

What to Unit Test ​

Use unit tests for service decisions, normalization, response mapping, and the business behavior called by a command, job, subscriber, or schedule. Include successful results, rejected inputs, and dependency failures relevant to the changed behavior.

For a fake dependency, assert the meaningful interaction, such as the ID passed to a repository or the absence of a write after validation fails. Keep transport status codes in HTTP tests and backend semantics in integration tests.

Avoid Full Runtime Boot ​

Construct the service or function directly. Starting HTTP, a worker, or the scheduler adds lifecycle and registration concerns to a test of business behavior. Add those checks when the boundary itself is what you need to prove.

Next Steps ​