Skip to content

Go Test Cache

DodaTech 1 min read

In this tutorial, you'll learn about Go Test: Cache Invalidation. We cover key concepts, practical examples, and best practices.

Test cache -- Understand Go's test caching and use -count=1 to force re-execution.

The Problem

Go caches test results when the test binary and source haven't changed. This is great for speed but confusing when you expect tests to re-run.

Wrong

go test ./...

Output:

// (cached) -- no output if nothing changed
// Tests may not actually run!
go test -count=1 ./...

Output:

// Tests always run. No caching.

Prevention

  • Use -count=1 to disable test caching
  • Cache based on source, env, and test binary
  • Tests with -short flag are cached separately
  • GOCACHE env var controls cache location
  • go clean -testcache clears test cache

Common Mistakes with test cache

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Why are my tests not running?**

Go cached the previous result. Use go clean -testcache or -count=1.

What invalidates the cache?

Code changes, test file changes, env vars listed in cache key.

Is caching good or bad?

Good for CI. Bad during development. Use -count=1 for dev.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro