惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
C
Cisco Blogs
WordPress大学
WordPress大学
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The Cloudflare Blog
小众软件
小众软件
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
Intezer
Cyberwarzone
Cyberwarzone
T
The Blog of Author Tim Ferriss
博客园 - Franky
F
Fortinet All Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
G
Google Developers Blog
Recent Announcements
Recent Announcements
I
InfoQ
T
Threat Research - Cisco Blogs
V
V2EX
T
Tenable Blog
H
Help Net Security
Cisco Talos Blog
Cisco Talos Blog
T
Tailwind CSS Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The GitHub Blog
The GitHub Blog
P
Privacy & Cybersecurity Law Blog
A
Arctic Wolf
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
D
DataBreaches.Net
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
D
Docker
T
Tor Project blog
Attack and Defense Labs
Attack and Defense Labs
P
Proofpoint News Feed
H
Heimdal Security Blog
Engineering at Meta
Engineering at Meta
雷峰网
雷峰网
Martin Fowler
Martin Fowler
AWS News Blog
AWS News Blog
IT之家
IT之家
Google DeepMind News
Google DeepMind News
NISL@THU
NISL@THU
Google Online Security Blog
Google Online Security Blog
Vercel News
Vercel News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
SecWiki News
SecWiki News
GbyAI
GbyAI
P
Proofpoint News Feed
月光博客
月光博客
Schneier on Security
Schneier on Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Refactoring Go API Unit Tests: Breaking Down the Testing Monolith
RL Loz · 2026-06-12 · via DEV Community

The Concept

When building backend APIs in Go, testing isn't just about code coverage, it's about long-term maintainability. As an application grows, a naive approach to unit testing can lead to "testing monoliths" where test setup, mocking, HTTP routing, and core business logic verification are jammed into a single, massive file.

To keep a codebase agile, your testing architecture must mirror the separation of concerns found in your production code. This means isolating the code that handles incoming network requests from the code that executes your core domain logic.


The What

Initially, the testing structure for the API lived entirely within a single, monolithic *_test.go file. Inside this file, everything was dumped together: Only service-layer assertions no HTTP request simulation, and handwritten mock structs for both the repository and service layers.

const UUID = "12345678-1234-5678-1234-567890123456"

type StockMovementTest struct {
    GetStockMovementsFunc         func(ctx context.Context, filters dto.BaseFilters) ([]models.StockMovement, int, error)
}

func (m *StockMovementTest) GetStockMovements(ctx context.Context, q dto.BaseFilters) ([]models.StockMovement, int, error) {
    if m.GetStockMovementsFunc != nil {
        return m.GetStockMovementsFunc(ctx, q)
    }

    return nil, 0, nil
}

func NewTestStockMovement(testStockMovementRepo *StockMovementTest) stock_movements.StockMovementService {
    emailSvc := mocks.NewTestEmailService()
    _, auditLogSvc := mocks.NewTestAuditService()
    awsSvc := mocks.NewTestAWSService()

    return stock_movements.NewStockMovementService(testStockMovementRepo, emailSvc, nil, auditLogSvc, awsSvc)
}

func TestGetStockMovements(t *testing.T) {
    testStockMovementRepo := &StockMovementTest{}
    testStockMovementSvc := NewTestStockMovement(testStockMovementRepo)

    t.Run("Get StockMovements", func(t *testing.T) {
        testStockMovementRepo.GetStockMovementsFunc = func(ctx context.Context, q dto.BaseFilters) ([]models.StockMovement, int, error) {
            CheckStockMovementQuery(t, q)
            return []models.StockMovement{{ProductID: 1}}, 1, nil
        }

        query := dto.Query{Search: "test", Limit: 10, Offset: 2, Sort: "change_amount ASC"}
        _, _, err := testStockMovementSvc.GetStockMovements(context.Background(), query)

        if err != nil {
            t.Errorf("Expected no error, got %v", err)
        }
    })
}

The Why

While a single-file approach works for small projects, it quickly becomes an anti-pattern due to two major pain points:

  • Code Bloating: A single file containing setup, table-driven test cases, and verbose mock definitions quickly grows to thousands of lines, making it incredibly difficult to navigate and maintain.
  • Circular Dependencies (Cyclic Imports): In Go, packages cannot import each other transitively. When mocks, domain logic, and HTTP transport layers are tightly coupled in tests, you risk hitting compilation errors because the boundaries between your database, service, and handler packages become blurred.

Separating these concerns ensures that your tests remain clean, compile quickly, and scale alongside your features.

The How

To resolve this, the monolithic test file was refactored into a modular structure by breaking it down into three distinct components: mock.go, *_service_test.go, and *_handler_test.go.

📂 package_test/
├── 📄 mock.go              # Shared mock definitions for service & repository layers
├── 📄 *_service_test.go    # Pure business logic unit tests
└── 📄 *_handler_test.go    # HTTP, routing, and request/response validation tests

// mock.go

type MockAuthService struct {
    //
}

func (m *MockAuthService) GenerateToken(userID int64) (string, error) {
    return "", nil
}

func (m *MockAuthService) ParseToken(token string) (int64, error) {
    return 0, nil
}

func (m *MockAuthService) Login(ctx context.Context, req LoginRequest) (string, error) {
    return "", nil
}

func (m *MockAuthService) Register(ctx context.Context, req RegisterRequest) error {
    return nil
}

type MockAuthRepository struct {
    GetUsernameOrEmailFunc func(ctx context.Context, username string) (*models.Users, error)
    RegisterFunc           func(ctx context.Context, user *models.Users) error
}

func (m *MockAuthRepository) Register(ctx context.Context, user *models.Users) error {
    if m.RegisterFunc != nil {
        return m.RegisterFunc(ctx, user)
    }

    return nil
}

func (m *MockAuthRepository) GetUsernameOrEmail(ctx context.Context, username string) (*models.Users, error) {
    if m.GetUsernameOrEmailFunc != nil {
        return m.GetUsernameOrEmailFunc(ctx, username)
    }

    return &models.Users{}, nil
}

// *_service_test.go

var testAuthRepo = &auth.MockAuthRepository{}
var testAuthSvc = NewTestAuth(testAuthRepo)

func NewTestAuth(testAuthRepo *auth.MockAuthRepository) auth.AuthService {
    config := &config.Config{JWTSecretKey: "airconcure_jwt_key"}

    return auth.NewAuthService(testAuthRepo, config)
}

func TestAuthServiceLogin(t *testing.T) {
    t.Run("login credentials", func(t *testing.T) {
        testAuthRepo.GetUsernameOrEmailFunc = func(ctx context.Context, username string) (*models.Users, error) {
            passwordHash, _ := bcrypt.GenerateFromPassword([]byte("!Abc1234"), bcrypt.DefaultCost)
            user := &models.Users{
                ID:       1,
                Username: "test_account",
                Email:    "test_account@local.com",
                Password: string(passwordHash),
            }

            return user, nil
        }

        req := auth.LoginRequest{
            Username: "rdev",
            Password: "!Abc1234",
        }

        _, err := testAuthSvc.Login(context.Background(), req)
        if err != nil {
            t.Errorf("Expected no error, got %v", err)
        }
    })
}

// *_handler_test.go

var testAuthHandler = auth.NewAuthHandler(&auth.MockAuthService{})

func TestAuthHandlerLogin(t *testing.T) {
    type loginRequest struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }

    tests := []struct {
        name           string
        url            string
        requestBody    any
        expectedStatus int
    }{
        {
            name: "complete login credentials",
            url:  "/login",
            requestBody: loginRequest{
                Username: "rdev",
                Password: "!Abc1234",
            },
            expectedStatus: http.StatusOK,
        },
        {
            name: "login no password",
            url:  "/login",
            requestBody: loginRequest{
                Username: "rdev",
                Password: "",
            },
            expectedStatus: http.StatusBadRequest,
        },
        {
            name: "login password less than minimum required",
            url:  "/login",
            requestBody: loginRequest{
                Username: "rdev",
                Password: "1234",
            },
            expectedStatus: http.StatusBadRequest,
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            ctx, w := helpers.SetupJSONTestContext(t, http.MethodPost, tt.url, tt.requestBody)

            testAuthHandler.Login(ctx)

            if w.Code != tt.expectedStatus {
                t.Errorf("Login() status = %d, resp = %v, want %d", w.Code, w.Body, tt.expectedStatus)
            }
        })
    }
}

1. Centralizing Mocks (mock.go)

Instead of rewriting or copy-pasting mock implementations across multiple test files, all repository and service mock structs are declared once inside a dedicated mock.go file within the package. This acts as a single source of truth for test doubles.

2. Testing the Business Logic (*_service_test.go)

This file focuses strictly on testing the "under-the-hood" domain logic. Because the database/repository layer is mocked out via mock.go, these tests run entirely in-memory and are incredibly fast. They validate:

  • Data validation rules and edge cases.
  • Handling of incorrect data types or malformed payloads.
  • Domain-specific error handling and state transitions.

3. Testing the HTTP Transport Layer (*_handler_test.go)

This file is dedicated to verifying how the API interacts with the outside world. It uses Go's net/http/httptest package to simulate client requests, utilizing the service mocks so it doesn't trigger actual business logic. These tests validate:

  • HTTP status codes (e.g., 200 OK, 400 Bad Request, 429 Too Many Requests).
  • JSON serialization and deserialization.
  • Query parameters, URL parameters, and headers.
  • Middleware execution, such as rate limiters and authentication checks.

The Trade-offs

Like any architectural decision, moving to a multi-file testing structure comes with balancing factors:

Pros:

  • High Scannability: Developers looking for a routing bug only need to open the handler test, while those fixing a calculation bug can go straight to the service test.
  • Reduced Friction: Isolating the mocks prevents cyclic imports, keeping the Go compiler happy.
  • Clear Boundaries: It enforces discipline, ensuring you don't accidentally test HTTP mechanics inside a business logic test.

Cons:

  • Boilerplate Overhead: Managing multiple files and orchestrating mocks requires slightly more upfront configuration and file management.
  • Mock Maintenance: If a service interface changes, the central mock.go file must be manually updated (unless you adopt a code-generation tool like mockery).

In Layman's Terms

Imagine you run a busy restaurant.

Originally, your test kitchen had one giant manual that crammed the cook’s recipes, the waiter’s serving rules, and cardboard cutouts of fake customers all onto the same page. It was crowded and confusing.

With this new approach, you split that manual into three neat folders:

  1. The Prop Room (mock.go): This is where you keep all your cardboard cutouts (fake databases and fake chefs) so you can reuse them whenever you need to practice.
  2. The Kitchen Manual (*_service_test.go): This is where you test the food itself. Does it taste right? Is it missing an ingredient? You don't care how the waiter delivers it; you just care that the recipe works perfectly.
  3. The Dining Room Manual (*_handler_test.go): This is where you test the customer experience. Did the waiter smile? Was the bill calculated correctly? Is the host stopping too many people from rushing the door at once (rate limiting)? You don't care how the kitchen cooked the food here; you just care that the service at the table is seamless.

Conclusion

While software architecture preferences always vary depending on team conventions, decoupling your tests by responsibility is a proven strategy for Go applications. By isolating your HTTP logic from your business logic and centralizing your mocks, you eliminate code bloat, wipe out cyclic imports, and create a test suite that is easy to read, navigate, and maintain.