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

推荐订阅源

U
Unit 42
T
Threatpost
C
CERT Recently Published Vulnerability Notes
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Security Archives - TechRepublic
Security Archives - TechRepublic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
Project Zero
Project Zero
H
Heimdal Security Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Know Your Adversary
Know Your Adversary
Google Online Security Blog
Google Online Security Blog
W
WeLiveSecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
N
News | PayPal Newsroom
Hacker News - Newest:
Hacker News - Newest: "LLM"
H
Hacker News: Front Page
L
LINUX DO - 热门话题
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
Cloudbric
Cloudbric
V
Vulnerabilities – Threatpost
Hacker News: Ask HN
Hacker News: Ask HN
S
Securelist
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
TaoSecurity Blog
TaoSecurity Blog
NISL@THU
NISL@THU
N
News and Events Feed by Topic
S
Security Affairs
The Last Watchdog
The Last Watchdog
T
Tor Project blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
P
Palo Alto Networks Blog
AWS News Blog
AWS News Blog
P
Proofpoint News Feed
C
Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
LINUX DO - 最新话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tenable Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
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
ABAP Unit Testing with Test Doubles and Mocking Frameworks: A Senior Architects Guide to Isolating Dependencies in SAP S/4HANA
Oktay Ates · 2026-05-26 · via DEV Community

If yoy have been writing ABAP unit tests for a while, you have probably hit the same wall I did years ago: your tests pass in isolation but become brittle the moment they touch a database table, a remote function call, or a business object manager. The root cause is almost always the same—uncontrolled dependencies. Learning how to isolate those dependencies using ABAP test doubles and mocking frameworks is one of the most impactful skills a senior SAP developer can develop. This guide walks you through that skill in depth, with real-world patterns you can apply immediately.

Before we dive in, if you haven't read my earlier articles on ABAP unit testing in SAP S/4HANA and writing reliable, maintainable tests for real SAP systems, I’d recommend starting there. This article builds on those foundations and takes you to the next level: true dependency isolation.

Why Dependency Isolation Matters More Than You Think

Let me paint a picture you will recognize. You write a clean ABAP class—ZCL_ORDER_PROCESSOR—and it works perfectly. You even write a unit test. But your test calls the real BAPI_SALESORDER_CREATEFROMDAT2, which creates actual sales orders in your development client. Your test suite runs for 40 seconds. A colleague runs it on a different system and it fails because the customer number doesn't exist there.

That's not a unit test. That's an integration test wearing a unit test costume.

True unit tests must be:

  • Fast — Milliseconds, not seconds

  • Isolated — No database, no RFC, no file system

  • Deterministic — Same result every time, on every system

  • Self-contained — No setup data required outside the test class

Achieving this requires controlling your dependencies—and that means test doubles.

The Four Types of Test Doubles You Need to Know

The terminology here comes from Gerard Meszaros; classic work on xUnit patterns, and it maps cleanly to ABAP:

1. Dummy Objects

Passed around but never actually used. Often used to fill parameter lists when the value doesn’t matter for the test case at hand.

2. Stubs

Return canned answers to calls made during the test. They don't verify anything—they just provide predefined responses. Use these when your class under test reads data from a dependency.

3. Mocks

Pre-programmed with expectations about which calls they should receive. They verify behavior—meaning they fail your test if an expected method was not called or was called with wrong parameters.

4. Fakes

Working implementations that take shortcuts—an in-memory repository instead of a real database, for example. These are the most sophisticated and most useful in complex ABAP scenarios.

In practice, the ABAP Test Double Framework blurs these categories a bit, but understanding the conceptual distinction shapes how you design your tests.

Setting Up Your Architecture for Testability

You can't retrofit test doubles onto poorly structured code. The single most important prerequisite is dependency injection. If your class instantiates its own dependencies internally, you have no way to replace them in tests.

Here’s the pattern I use in every project:


"--- Interface Definition ---
INTERFACE zif_order_repository.
  METHODS:
    get_open_orders
      IMPORTING iv_customer TYPE kunnr
      RETURNING VALUE(rt_orders) TYPE ztorder_tab
      RAISING   zcx_order_not_found.
ENDINTERFACE.

"--- Production Implementation ---
CLASS zcl_order_repository DEFINITION PUBLIC CREATE PUBLIC.
  PUBLIC SECTION.
    INTERFACES zif_order_repository.
ENDCLASS.

CLASS zcl_order_repository IMPLEMENTATION.
  METHOD zif_order_repository~get_open_orders.
    SELECT * FROM ztorders
      WHERE customer = @iv_customer
        AND status  = 'OPEN'
      INTO TABLE @rt_orders.
    IF rt_orders IS INITIAL.
      RAISE EXCEPTION TYPE zcx_order_not_found.
    ENDIF.
  ENDMETHOD.
ENDCLASS.

"--- Consumer Class (Dependency Injected) ---
CLASS zcl_order_processor DEFINITION PUBLIC CREATE PUBLIC.
  PUBLIC SECTION.
    METHODS:
      constructor
        IMPORTING io_repository TYPE REF TO zif_order_repository,
      process_customer_orders
        IMPORTING iv_customer TYPE kunnr
        RETURNING VALUE(rv_count) TYPE i
        RAISING   zcx_order_not_found.
  PRIVATE SECTION.
    DATA mo_repository TYPE REF TO zif_order_repository.
ENDCLASS.

CLASS zcl_order_processor IMPLEMENTATION.
  METHOD constructor.
    mo_repository = io_repository.
  ENDMETHOD.

  METHOD process_customer_orders.
    DATA(lt_orders) = mo_repository->get_open_orders( iv_customer ).
    rv_count = lines( lt_orders ).
    " ... additional processing logic ...
  ENDMETHOD.
ENDCLASS.

Notice that ZCL_ORDER_PROCESSOR depends on the interface ZIF_ORDER_REPOSITORY, not the concrete class. This is the foundation that makes every test double strategy possible. This principle aligns directly with the clean code and refactoring principles I have covered previously—clean architecture and testability go hand in hand.

Using the ABAP Test Double Framework (TDF)

SAP’s built-in Test Double Framework, available since ABAP 7.50, lets you create mock objects for any interface without writing a separate test class. It’s powerful, but it requires you to understand its configuration model.

Step 1: Create the Test Double


CLASS ltc_order_processor_test DEFINITION FINAL FOR TESTING
  DURATION SHORT RISK LEVEL HARMLESS.

  PRIVATE SECTION.
    DATA:
      mo_cut        TYPE REF TO zcl_order_processor,
      mo_repo_mock  TYPE REF TO zif_order_repository.

    METHODS:
      setup,
      test_returns_correct_order_count FOR TESTING,
      test_raises_exception_when_no_orders FOR TESTING.
ENDCLASS.

CLASS ltc_order_processor_test IMPLEMENTATION.

  METHOD setup.
    " Create the test double using TDF
    mo_repo_mock = CAST zif_order_repository(
      cl_abap_testdouble=>create( 'ZIF_ORDER_REPOSITORY' )
    ).

    " Inject it into the class under test
    mo_cut = NEW zcl_order_processor( mo_repo_mock ).
  ENDMETHOD.

Step 2: Configure Stub Behavior


  METHOD test_returns_correct_order_count.
    " Arrange: define what the mock returns
    DATA(lt_fake_orders) = VALUE ztorder_tab(
      ( order_id = '1000000001' customer = '0000001000' status = 'OPEN' )
      ( order_id = '1000000002' customer = '0000001000' status = 'OPEN' )
      ( order_id = '1000000003' customer = '0000001000' status = 'OPEN' )
    ).

    cl_abap_testdouble=>configure_call( mo_repo_mock
      )->returning( lt_fake_orders
      )->when_invoked( ).

    mo_repo_mock->get_open_orders( '0000001000' ).

    " Act
    DATA(lv_count) = mo_cut->process_customer_orders( '0000001000' ).

    " Assert
    cl_abap_unit_assert=>assert_equals(
      act = lv_count
      exp = 3
      msg = 'Expected 3 open orders for customer 1000'
    ).
  ENDMETHOD.

Step 3: Verify Exception Handling


  METHOD test_raises_exception_when_no_orders.
    " Configure mock to raise the exception
    cl_abap_testdouble=>configure_call( mo_repo_mock
      )->raising( NEW zcx_order_not_found( ) 
      )->when_invoked( ).

    mo_repo_mock->get_open_orders( '9999999999' ).

    " Act & Assert
    TRY.
      mo_cut->process_customer_orders( '9999999999' ).
      cl_abap_unit_assert=>fail(
        msg = 'Expected ZCX_ORDER_NOT_FOUND to be raised'
      ).
    CATCH zcx_order_not_found.
      " Test passes  exception was correctly propagated
    ENDTRY.
  ENDMETHOD.

ENDCLASS.

This is clean, readable, and—critically—requires zero database access. The test runs in milliseconds and produces the exact same result on every system, every time.

Building a Fake Repository for Complex Scenarios

Sometimes the TDF's stub configuration becomes verbose when you have many method calls with different parameter combinations. In those cases, I prefer writing a fake implementation—a lightweight in-memory version of the real dependency.


"--- Fake Repository (defined inside the test include) ---
CLASS ltc_fake_order_repository DEFINITION FINAL.
  PUBLIC SECTION.
    INTERFACES zif_order_repository.
    DATA mt_orders TYPE ztorder_tab.  " Test data injected directly
ENDCLASS.

CLASS ltc_fake_order_repository IMPLEMENTATION.
  METHOD zif_order_repository~get_open_orders.
    rt_orders = FILTER #( mt_orders
      USING KEY primary_key
      WHERE customer = iv_customer
        AND status   = 'OPEN' ).
    IF rt_orders IS INITIAL.
      RAISE EXCEPTION TYPE zcx_order_not_found.
    ENDIF.
  ENDMETHOD.
ENDCLASS.

Using the fake in a test becomes extremely readable:


  METHOD test_with_fake_repository.
    " Arrange
    DATA(lo_fake_repo) = NEW ltc_fake_order_repository( ).
    lo_fake_repo->mt_orders = VALUE #(
      ( order_id = '2000000001' customer = '0000002000' status = 'OPEN' )
      ( order_id = '2000000002' customer = '0000002000' status = 'OPEN' )
      ( order_id = '2000000003' customer = '0000002000' status = 'BLOCKED' ) " Should not be counted
    ).

    DATA(lo_cut) = NEW zcl_order_processor( lo_fake_repo ).

    " Act
    DATA(lv_count) = lo_cut->process_customer_orders( '0000002000' ).

    " Assert  only OPEN orders should be counted
    cl_abap_unit_assert=>assert_equals(
      act = lv_count
      exp = 2
      msg = 'Only OPEN orders should be processed'
    ).
  ENDMETHOD.

Fakes are particularly powerful when you need to test multiple method calls, stateful behavior, or complex filtering logic. They are slightly more work to write but dramatically more flexible. The alignment here with good exception handling design is important too—see my detailed series on class-based exception architecture to understand how to propagate errors cleanly from your fakes.

Handling CDS Views and Database Access in Tests

One of the trickiest scenarios in modern SAP development is testing code that reads from CDS views. If your class calls a CDS view directly via inline SELECT, you can't easily mock it without architectural changes.

The solution is to wrap CDS access in a repository interface—exactly the pattern shown above. Your production repository queries the CDS view; your test uses a fake or mock. This approach integrates naturally with the layered CDS architecture I’ve described in the CDS Views performance optimization series—the interface boundary between your CDS consumption layer and business logic layer is also your testability boundary.

If you absolutely must test with real CDS data, use ABAP's test seams (introduced in 7.40) as a last resort—but treat them as a code smell that signals a refactoring opportunity.

Common Mistakes and How to Avoid Them

Mistake 1: Testing the Mock, Not the Logic

A surprisingly common mistake is writing a test where the only thing being verified is that the mock returns what you told it to return. Ask yourself: am I testing the behavior of my class under test, or just the wiring of my test setup?

Mistake 2: Over-specification

Configuring your mock to verify that a method was called with exactly these parameters in exactly this order makes your tests fragile. Mock behavior, not implementation details. If the internal call sequence of a method isn't part of its public contract, don't assert on it.

Mistake 3: Sharing Mutable State Between Tests

Always create fresh test doubles in the SETUP method. If one test modifies the state of a fake repository and the next test inherits that state, you get mysterious, order-dependent failures. This is one of the hardest bugs to diagnose in test suites.

Mistake 4: Ignoring the Refactoring Cost

Retrofitting dependency injection into tightly coupled legacy code is hard. Be honest about the cost. I’ve seen teams spend more time fighting legacy code structure than writing actual tests. Prioritize testability in new code; tackle legacy code incrementally with the techniques in my clean code refactoring guide.

Structuring Your Test Classes for Maintainability

As your test suite grows, organization becomes critical. Here is the structure I recommend:

  • One test class per behavior scenario — Don't cram all tests into a single LTC_ class. Use separate local test classes for distinct behaviors (happy path, error cases, edge cases).

  • Descriptive method names — test_returns_zero_when_customer_has_no_open_orders is far more useful than test_01 when diagnosing failures at 2am.

  • Arrange-Act-Assert structure — Every test method should follow this pattern. It makes tests readable at a glance and forces you to think clearly about what you’re actually testing.

  • Short test methods — If a test method exceeds 20-25 lines, it's probably testing too many things. Split it.

Key Takeaways

After years of building and reviewing ABAP systems, here is what I can tell you with confidence:

  • Test doubles are not a testing luxury—they’re a design quality indicator. If you can't mock a dependency, your architecture has a coupling problem.

  • The ABAP Test Double Framework is production-ready and sufficient for most scenarios. Learn it deeply before reaching for more complex solutions.

  • Fake implementations are your best friend when testing complex stateful interactions. Don’t be afraid to write them—they’re part of your test suite, not production code overhead.

  • Dependency injection via constructor is the single most important pattern for ABAP testability. Apply it consistently in all new code.

  • Clean test code is just as important as clean production code. Treat your test classes with the same architectural discipline you apply to your business classes.

What's Next?

In the next article in this testing series, I will tackle one of the most requested topics from my readers: testing RAP business objects and ABAP RESTful application handlers—where the frameworks built-in test infrastructure opens up some genuinely exciting possibilities. Stay tuned.

In the meantime, pick one class in your current project that has no tests. Identify its external dependencies. Draw the interface boundaries. Then write your first test double. That first step is almost always the hardest—and the most rewarding.

Have questions about a specific mocking scenario you are struggling with? Drop a comment below—I read every one and do my best to respond with concrete advice.