How MockLayer Works

How MockLayer handles requests, what it supports, how to configure and secure it, and where its limits are.

What is MockLayer?

MockLayer is a standalone HTTP server that answers SAP OData requests with generated mock data. It reads the service's EDMX metadata and generates values from the declared EDM types (types it does not cover come back as null; see step 4).

Point your application at MockLayer instead of SAP. MockLayer contacts SAP only to fetch $metadata, or not at all if you upload the EDMX file and leave Sap__Host empty. Your data requests never reach SAP.

In short: the same OData URLs as SAP, data generated from the EDMX, no stub files. MockLayer is a tool for development and testing.

How Does It Work?

1

Request Routing

Your application sends its OData requests to MockLayer instead of SAP:

Before: http://sap-server:8000/sap/opu/odata/...
After: http://localhost:5000/sap/opu/odata/...

MockLayer handles requests under /sap/opu/odata/* (answered in OData V2 JSON format) and /sap/opu/odata4/* (OData V4 JSON format). The first two path segments after that prefix name the service, for example /sap/opu/odata/iwbep/gwsample_basic.

2

Metadata Loading (Two Ways)

MockLayer needs the service's EDMX metadata. It gets it in one of two ways:

Option 1: Automatic Fetch from SAP

  • On the first request for a service, MockLayer fetches Sap__Host + service path + /$metadata. Query strings such as ?sap-client=100 are not passed on.
  • It parses the EDMX, caches it in memory and saves a copy to disk (Edmx__CacheDirectory).
  • When the cached copy is older than Edmx__TtlHours (default 24), the next request fetches it again. If SAP is unreachable, returns an error, or returns something that is not EDMX (for example an HTML logon page), MockLayer serves the cached copy: from memory, or from disk after a restart. With no cached copy, it answers HTTP 404 with a message that explains how to upload the EDMX.

Option 2: Upload the EDMX File

  • POST or PUT the EDMX file to the service's $metadata URL, with Content-Type application/xml or text/xml. Maximum request size: 10 MB.
  • MockLayer parses it and caches it for that service path, in memory and on disk.
  • No SAP connection needed. For offline use, leave Sap__Host empty (MockLayer then never contacts SAP), or set Edmx__TtlHours=0 (cached metadata never expires).
  • To clear the cached metadata of a service (memory and disk), send DELETE to its $metadata URL.
# bash. The single quotes keep $metadata literal. # Upload an EDMX file curl --fail -X POST -H "Content-Type: application/xml" \ --data-binary @metadata.edmx \ 'http://localhost:5000/sap/opu/odata/sap/MY_SERVICE/$metadata' # Clear the cached metadata of this service curl --fail -X DELETE 'http://localhost:5000/sap/opu/odata/sap/MY_SERVICE/$metadata'

Caution: MockLayer treats every non-empty POST or PUT with an XML or text Content-Type under a service path as an EDMX upload. A body that contains no entity types (for example an Atom entry) gets HTTP 400 and leaves the cached metadata unchanged. Send create and update requests with a JSON body.

What MockLayer reads from the EDMX: entity types, entity sets, keys, properties and their EDM types, complex types, and navigation properties ($expand uses V2-style associations only). It ignores facets such as MaxLength, Precision and Scale, and SAP annotations.

Cache observability: Responses built from metadata (mock data and $metadata) include X-MockLayer-Cache-Source (sap, memory, memory-stale, disk, request-body) and X-MockLayer-Cache-Age (seconds since MockLayer loaded that metadata into memory). Use them to debug stale schema issues.

3

Entity Matching

MockLayer maps the resource part of the URL (for example ProductSet in .../gwsample_basic/ProductSet('1')) to an entity type or entity set in the EDMX. It tries 11 matching rules in order and uses the first match:

1. Exact match (case-sensitive)
2. Add "Type" suffix
3. Remove "Type" suffix
4. Case-insensitive exact match
5. Case-insensitive + "Type" suffix
6. Plural to singular (remove 's')
7. Singular to plural (add 's')
8. EntitySet pattern (remove "Set"/"Collection")
9. Partial match (contains)
10. Reverse partial match
11. Fuzzy match (Levenshtein, 80%+ similarity)

Caution: rules 9 to 11 (partial and fuzzy matches) can pick a different type than you meant, without an error. URLs with a navigation segment, such as A_BusinessPartner('1')/to_BusinessPartnerAddress, go through the same rules, so the response can be the source type instead of the navigation target. In V2 responses, check __metadata.type. If no rule matches, MockLayer returns HTTP 404 with up to 20 available names.

4

Mock Data Generation

MockLayer generates each value from the property's EDM type. It uses the Bogus library and the property name to pick the kind of value:

String properties → chosen by name: names containing Email get an email address, City a city, Name a person's full name; names containing Number or Count get digits; other strings get a random first name
Numeric properties → random numbers in fixed ranges; names containing Price or Amount get money-like values
Key properties → numbered per entity: 1, 2, 3 for integer keys; "0000001", "0000002" for string keys
Edm.DateTime and Edm.DateTimeOffset → /Date(milliseconds)/ in V2, ISO 8601 (2026-01-31T10:00:00Z) in V4
Boolean properties → Random true/false
Navigation properties → Nested objects when you $expand them; levels follow your $expand path
Complex types → Nested objects built from their properties; nesting stops when a type repeats
Other types (not string, number, Boolean, date/time, Guid or binary) → null

Filter-aware: MockLayer parses $filter with Microsoft.OData.Core and puts the constrained values into the generated entities. For example, $filter=Category eq '2' produces entities where that property is exactly '2'. Supported: eq, ne, gt/ge/lt/le (numeric properties only), startswith, endswith and contains, joined with and. With or between eq comparisons on one property, each entity gets one of the values. MockLayer ignores a filter that it cannot parse.

Important: Mock data is generated on-the-fly for each request. No state is maintained between requests (stateless design), so the same request returns new random values each time.

5

OData Response Formatting

The generated data is wrapped in the OData JSON format. Example (V2, shortened; values are random):

// GET /sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner?$top=1 { "d": { "results": [ { "__metadata": { "id": "http://localhost:5000/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner('0000001')", "uri": "http://localhost:5000/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner('0000001')", "type": "API_BUSINESS_PARTNER.A_BusinessPartner" }, "BusinessPartner": "0000001", ... "BusinessPartnerFullName": "Maria Jensen", ... "CreationDate": "/Date(1745232813000)/", ... "BusinessPartnerIsBlocked": false, ... } ] } }

V2 (/sap/opu/odata/): d and results envelope, __metadata (id, uri, type) on each entity, and __count when you send $inlinecount=allpages or $count=true. V4 (/sap/opu/odata4/): value array, @odata.count, ISO 8601 dates, no __metadata. Data responses use Content-Type application/json; $metadata uses application/xml.

Differences from the OData specifications: In V2, Edm.Decimal, Edm.Int64 and Edm.Double values are JSON numbers; the OData V2 JSON format writes them as strings. Navigation properties that you do not $expand are not returned as __deferred links; they come back filled with generated entities. Property names that contain an underscore lose it and start with a capital letter (to_BusinessPartnerAddress becomes ToBusinessPartnerAddress, JP_SupplierCapitalAmountCrcy becomes JPSupplierCapitalAmountCrcy), except navigation properties added by $expand, so a $select on such a name returns nothing. A read by key puts the requested key in __metadata.uri, but the key property holds a generated value. Entities added by $expand have a __metadata.type without the namespace and a generated key in __metadata.uri, and leave out nullable properties that are not strings. __metadata.type is the last service path segment plus the matched entity set or type name (API_BUSINESS_PARTNER.A_BusinessPartner above), not the EDMX EntityType (API_BUSINESS_PARTNER.A_BusinessPartnerType). V4 responses have no @odata.context, which OData JSON Format 4.01 requires. Data responses are always JSON ($format and the Accept header are ignored), and responses carry no OData-Version or DataServiceVersion header.

Authentication & Security

Two Authentication Modes

MockLayer needs SAP credentials only to fetch $metadata. It never sends your data requests to SAP. For the $metadata request, it picks credentials in this order:

1

Header Forwarding (Recommended)

When MockLayer fetches $metadata, it copies the authentication headers of the request that triggered the fetch. It does not store them.

// Your app makes requests with your own auth headers fetch("http://localhost:5000/sap/opu/odata/.../ProductSet", { headers: { "Authorization": "Basic " + btoa("user:pass"), "sap-client": "100" } }); // MockLayer forwards these headers to your real SAP server // when it fetches $metadata, then returns mock data
  • No stored credentials - MockLayer keeps no SAP credentials in this mode
  • Personal credentials - Each developer's own credentials fetch $metadata. Fetched metadata is cached per service and shared by all callers
  • Header-based auth - Basic or Bearer (OAuth 2.0) in the Authorization header, plus an APIKey header. Cookies, SAML browser flows and client certificates are not forwarded

Forwarded headers: Authorization, sap-client, sap-language and APIKey, only on the $metadata request. Requests served from the cache do not contact SAP. URL parameters such as ?sap-client=100 are not forwarded: send sap-client as a header.

2

Configured Credentials (Fallback)

If the request has no Authorization header, MockLayer uses Sap__Username and Sap__Password (Basic authentication; both must be set), and Sap__Client as the sap-client header if the request has none.

# Linux/macOS (bash) export MOCKLAYER_LICENSE=your-license-key export Sap__Host=https://sap.company.com:8000 export Sap__Username=MOCKUSER export Sap__Password=your-password export Sap__Client=100 ./MockLayer.Service

Settings without secrets can also go in appsettings.json. Environment variables override it.

{ "Sap": { "Host": "https://sap.company.com:8000", "Client": "100", "ValidateSsl": true } }
  • →Useful for CI/CD: one read-only SAP technical user, with its password stored as a CI secret
  • →Credentials are optional - header forwarding works without them

Security Warning: Never commit credentials to source control. Pass them as environment variables from your CI secret store or a secret manager (for example Azure Key Vault or AWS Secrets Manager).

Security Defaults

MockLayer is a development and testing tool. It has no user accounts and no access control of its own.

  • 1.Localhost only by default. MockLayer listens on http://localhost:5000, so only the same machine can connect. To accept connections from other machines, set ASPNETCORE_URLS (for example http://0.0.0.0:5000), set ASPNETCORE_HTTP_PORTS, or start it with --urls. MockLayer then logs a warning at startup.
  • 2.No authentication. Anyone who can reach the port can read mock data and cached $metadata, upload EDMX files and clear the metadata cache. Open the port only to machines you trust, for example with a firewall rule.
  • 3.Plain HTTP. By default MockLayer serves plain HTTP, so Authorization headers that your app sends to MockLayer are not encrypted on the way. Keep that connection on the same machine or a trusted network.
  • 4.TLS to SAP. MockLayer validates the SAP server's TLS certificate (Sap__ValidateSsl=true by default). If SAP uses a certificate from your company's own certificate authority, add that CA to the operating system's trusted certificates. Set Sap__ValidateSsl=false only for a self-signed certificate in local development: MockLayer then accepts any certificate and logs a warning, and credentials sent to SAP can be intercepted.
  • 5.Read-only SAP user. Use a read-only SAP technical user. With Sap__Username and Sap__Password set, anyone who can reach MockLayer can make it fetch $metadata with that user for any service under /sap/opu/odata/ or /sap/opu/odata4/ on Sap__Host, and read the result.
  • 6.Secrets. Keep the license key and SAP credentials in your CI system's secrets or a secret manager, and pass them as environment variables. Never commit them.
  • 7.Rate limit. By default each client IP address can send 100 requests per minute; up to 10 more wait for the next minute; after that MockLayer answers HTTP 429 with Retry-After: 60. MockLayer counts by the connection's IP address and, by default, does not read X-Forwarded-For, so behind a reverse proxy all clients share one limit. Change it with RateLimit__PermitLimit and RateLimit__QueueLimit.

X-CSRF-Token Handling

MockLayer includes automatic X-CSRF-Token generation to satisfy SAP client libraries that request these tokens.

How It Works

  • 1.When a request includes the x-csrf-token: fetch header, MockLayer generates a random token: 32 random bytes, Base64-encoded (44 characters)
  • 2.The token is returned in the response header: x-csrf-token: [generated-token]
  • 3.Responses to other requests also carry a random x-csrf-token header (except license errors and rate-limit responses)
  • 4.Tokens are NOT validated - MockLayer accepts any token value since responses are stateless mocks
// Example: CSRF token fetch GET /sap/opu/odata/iwbep/gwsample_basic/ProductSet x-csrf-token: fetch // Response header: x-csrf-token: vK8j3nP9xQ...= (44-character Base64 string) // A new random token on every response // No validation: MockLayer accepts any token value

Why this matters: SAP OData clients such as SAPUI5 and the SAP Cloud SDK for JavaScript fetch an X-CSRF-Token by default (the SDK before every non-GET request). MockLayer answers these token requests, so this step succeeds. MockLayer returns mock data for write requests too, but it stores no changes (stateless design).

What MockLayer Supports

Supported Features

  • ✓Automatic metadata fetching from the SAP $metadata endpoint, cached in memory and on disk
  • ✓POST/PUT EDMX XML in the request body for offline use + DELETE $metadata to clear the cache
  • ✓$metadata requests (return the cached EDMX XML)
  • ✓Entity collections (e.g., /ProductSet): 3 entities unless you send $top
  • ✓Single entity by key (e.g., /ProductSet('001')): __metadata.uri (V2) uses your key; the key property holds a generated value
  • ✓OData V2 JSON format, and a simplified V4 JSON shape under /odata4/ (no @odata.context; $expand and some V4 types are not supported there)
  • ✓Complex types and nested structures
  • ✓Navigation properties through $expand, including multi-level paths (for example to_Address/to_Email)
  • ✓Header forwarding (Authorization, sap-client, sap-language, APIKey) for the $metadata fetch
  • ✓X-CSRF-Token generation for SAP client compatibility
  • ✓Query options: $filter, $select, $expand, $orderby, $top (sets how many entities are generated), $count=true, $inlinecount=allpages

⚠Not Supported

  • ✗State management (no data persistence between requests)
  • ✗Real writes — POST, PUT, PATCH, MERGE and DELETE return HTTP 200 with generated data (not 201 or 204) and store nothing. Exceptions: POST or PUT with an XML or text body is an EDMX upload; DELETE on $metadata clears the cache.
  • ✗Paging and search — $skip and $skiptoken are ignored (each request generates new data); $search is accepted and ignored
  • ✗/$count path segment — returns a collection, not a number
  • ✗Function imports, actions and batch requests ($batch)
  • ✗Service document — the service root URL returns generated data for one EDMX type, not the list of entity sets
  • ✗$expand with V4 EDMX — MockLayer reads navigation targets only from V2-style associations
  • ✗Longer service paths — MockLayer uses only the first two segments after the prefix as the service path, also for the $metadata fetch
  • ✗EDMX facets — MaxLength, Precision and Scale are not applied to generated values
  • ✗CORS — MockLayer sends no CORS headers, so browser code on another origin cannot call it directly
  • ✗Recording/replay, user-defined responses, custom mock data or simulated SAP errors

Why? MockLayer generates every mock response from the EDMX and, by design, keeps no data between requests. It cannot return data that you wrote earlier.

Use Cases

✅ Good Fit

  • Backend integration tests that check entity structures and data types
  • CI/CD pipelines where SAP is unavailable or unreliable (upload the EDMX)
  • Local development without VPN or SAP access
  • Mapping checks: does your code read the entity sets and properties defined in the EDMX (mind the format differences above)
  • Exploring an SAP API's data structure from its EDMX before you have access to the SAP system

❌ NOT Suitable For

  • Testing CRUD operations (create, update, delete)
  • Validating business logic in SAP (e.g., price calculations, stock checks)
  • Testing error handling (MockLayer cannot return SAP error responses)
  • Benchmarking real SAP performance (responses are generated, not from SAP)
  • Replacing a full SAP sandbox for end-to-end testing

Quick Start Example

1. Start MockLayer (Linux/macOS, bash)

export MOCKLAYER_LICENSE=your-license-key export Sap__Host=https://your-sap-server:8000 ./MockLayer.Service # Startup log: MockLayer listening on http://localhost:5000

2. Point your app to MockLayer

// Before const baseUrl = "https://sap-server:8000"; // After const baseUrl = "http://localhost:5000";

3. Make requests as usual

fetch("http://localhost:5000/sap/opu/odata/iwbep/gwsample_basic/ProductSet", { headers: { "Authorization": "Basic " + btoa("user:pass") } }) .then(res => res.json()) .then(data => console.log(data.d.results)); // On the first request, MockLayer: // 1. Fetches $metadata from your SAP server with your Authorization header // 2. Generates ProductSet entities from the EDMX types (3 by default) // 3. Returns them in the OData V2 JSON format

That's it!

No stub files and no hand-written JSON responses: MockLayer builds the responses from the service's EDMX metadata. No SAP access? Upload the EDMX file instead (Metadata Loading, option 2).

Deployment

MockLayer.Service is a self-contained executable for Windows (x64), Linux (x64, arm64) and macOS (Intel, Apple silicon). You do not need to install .NET.

Standalone Binary

Run on Windows, Linux, or macOS

Download Binaries

Download the latest release:

Download Page

• Windows (x64): mocklayer-service-win-x64.zip

• Linux (x64): mocklayer-service-linux-x64.tar.gz

• Linux (arm64): mocklayer-service-linux-arm64.tar.gz

• macOS (Intel): mocklayer-service-osx-x64.tar.gz

• macOS (Apple silicon): mocklayer-service-osx-arm64.tar.gz

The Linux builds need glibc and the system libraries that .NET 9 uses, such as OpenSSL and ICU (Microsoft's list). There is no build for Alpine Linux (musl). For operating system versions, see the .NET 9 supported OS list.

Linux/macOS

# Extract into a new folder (the archive has no top-level folder). # Use the file name for your platform, e.g. mocklayer-service-osx-arm64.tar.gz mkdir mocklayer-service tar -xzf mocklayer-service-linux-x64.tar.gz -C mocklayer-service cd mocklayer-service # Set environment variables export MOCKLAYER_LICENSE="your-license-key" export Sap__Host="https://sap.company.com:8000" # Run (listens on http://localhost:5000) ./MockLayer.Service

Windows

REM Command Prompt (cmd.exe). Extract the ZIP file, then: set MOCKLAYER_LICENSE=your-license-key set Sap__Host=https://sap.company.com:8000 REM Run (listens on http://localhost:5000) MockLayer.Service.exe
# PowerShell $env:MOCKLAYER_LICENSE = "your-license-key" $env:Sap__Host = "https://sap.company.com:8000" .\MockLayer.Service.exe

Linux Systemd Service

# Create systemd service file: /etc/systemd/system/mocklayer.service [Unit] Description=MockLayer OData mock server After=network.target [Service] Type=simple WorkingDirectory=/opt/mocklayer-service ExecStart=/opt/mocklayer-service/MockLayer.Service # File with MOCKLAYER_LICENSE=... and Sap__...=... lines (chmod 600) EnvironmentFile=/etc/mocklayer/mocklayer.env Restart=on-failure User=mocklayer Group=mocklayer [Install] WantedBy=multi-user.target # The mocklayer user needs write access to WorkingDirectory: # with the default settings, MockLayer creates edmx-cache/ and logs/ there. # Enable and start sudo systemctl daemon-reload sudo systemctl enable mocklayer sudo systemctl start mocklayer

Environment Variables Reference

VariableRequiredDescriptionExample
MOCKLAYER_LICENSEYesYour license key from trial or subscription. Environment variable only. Read once at startup: restart MockLayer after you change it.MOCKLAYER-STD-...
Sap__HostOptional*SAP server URL (protocol + host + port only). MockLayer fetches Sap__Host + service path + /$metadata.https://sap.company.com:8000
Sap__UsernameNoFallback SAP user, used when a request has no Authorization header. Needs Sap__Password.MOCKUSER
Sap__PasswordNoPassword of the fallback SAP user••••••••
Sap__ClientNoSAP client, sent as the sap-client header together with the fallback user, if the request has no sap-client header100
Sap__ValidateSslNoValidate the SAP server's TLS certificate. Default: true. false accepts any certificate and logs a startup warning: use it only for a self-signed certificate in local development.true
Edmx__CacheDirectoryNoFolder for the EDMX disk cache. A relative path starts at the working directory. Default: ./edmx-cache./edmx-cache
Edmx__TtlHoursNoHours until cached metadata is fetched from SAP again. Default: 24. 0 = never expires.24
RateLimit__PermitLimitNoRequests per minute per client IP address, /health included. Default: 100. 0 turns the limit off.100
RateLimit__QueueLimitNoRequests that wait for the next minute once the limit is reached. Default: 10. Requests beyond that get HTTP 429 with Retry-After: 60.10
ASPNETCORE_URLSNoListening address. Default: http://localhost:5000 (this machine only). The --urls command-line option does the same.http://0.0.0.0:5000
ASPNETCORE_HTTP_PORTSNoPort(s) to listen on, on all network interfaces5000

*Note on Sap__Host: Only required if automatically fetching metadata from SAP. If you upload the EDMX file, MockLayer works without a SAP connection. The Sap, Edmx and RateLimit settings can also go in appsettings.json (for example section Sap, key Host); environment variables override it.

Health Check and License

GET /health works even when the license is not valid, so you can monitor it. It answers HTTP 200 when the license allows requests and HTTP 503 when it does not.

// GET http://localhost:5000/health → HTTP 200 { "status": "healthy", // "unhealthy" with HTTP 503 "service": "MockLayer", "version": "<release version>", "timestamp": "<current time, UTC>", "license": { "status": "Valid", // Valid | ExpiringSoon | Expired | Invalid "tier": "Standard", // Trial | Standard | Growth | Enterprise (null if invalid) "is_valid": true, "message": "License valid until 2026-12-03", "expiry_date": "2026-12-03T00:00:00", "days_until_expiry": 30, "grace_period_days": 7 } }
  • →A key is valid through the end of its expiry date (UTC). The date is part of the key: a key that starts with MOCKLAYER-STD-20261203 expires on 3 December 2026.
  • →Key lifetime: trial keys expire 5 days after issue, monthly keys one calendar month after issue, annual keys one year after issue.
  • →Grace period after the expiry date: Standard 7 days, Growth and Enterprise 14 days, trial none. Requests keep working during the grace period.
  • →Responses that pass the license check carry X-MockLayer-Tier, X-MockLayer-License-Status and X-MockLayer-Days-Until-Expiry. From as many days before the expiry date as the grace period lasts, until the grace period ends, they also carry X-MockLayer-Warning.
  • →MockLayer checks the key again once per UTC day, so a running instance also stops when the grace period ends. From then on, every request except /health gets HTTP 403 with a JSON body (error, message, help, upgrade_url).
  • →MockLayer reads MOCKLAYER_LICENSE only at startup. After you set a new key, restart MockLayer.

Where to Run It

MockLayer.Service is a console application that serves HTTP. Run it close to the code that calls it.

Developer machine

  • • Windows, Linux or macOS
  • • Listens on localhost:5000 by default

CI runner

  • • Start it in the background; wait until /health returns 200
  • • Upload the EDMX file, then run your tests
  • • License key and SAP credentials from CI secrets

Shared server or VM

  • • Linux systemd service (see above)
  • • Set ASPNETCORE_URLS to accept remote connections
  • • Allow only trusted clients (firewall)

Not tested

  • • PaaS hosts (Azure App Service, AWS Elastic Beanstalk, Google App Engine)
  • • Windows service wrappers (for example NSSM)

Self-hosted: MockLayer.Service never contacts MockLayer servers and checks the license key locally. By default, its only outbound requests are the $metadata fetches from the host in Sap__Host. With EDMX upload and an empty Sap__Host, it needs no SAP access and no internet access. Optional: if you set ApplicationInsights__InstrumentationKey, it also sends its log entries to your Azure Application Insights resource.