How to Mock SAP OData Services in Your CI/CD Pipeline
The Contract SAP Already Publishes
Every SAP OData service exposes a $metadata endpoint. It returns an EDMX document — XML that describes every entity type, every property, every navigation relationship, and every data type in the service.
API_BUSINESS_PARTNER alone defines 65 entity types. $metadata describes all of them: the data types (Edm.String, Edm.DateTime, Edm.Decimal), the nullable flags, the key fields, the navigation paths. It is a machine-readable description of the service's structure, at a well-known URL.
Stub-based mocking ignores this. It asks developers to hand-write information that $metadata already provides.
Why SAP OData Is Harder to Mock Than REST
Before comparing approaches, here is what makes SAP OData structurally different from a typical JSON API. A generic mock tool leaves every one of these details to you.
Protocol envelopes. OData V2 wraps entity collections in {"d": {"results": [...]}} with __metadata objects on each entity containing URIs and type names. OData V4 uses {"value": [...]} with @odata.context annotations.
A mock that returns a plain JSON array breaks clients that expect the envelope. SAP Cloud SDK for JavaScript, for example, logs a warning and returns an empty list when a V2 collection response has no d.results.
Date encoding. SAP OData V2 serializes Edm.DateTime values as /Date(1672531200000)/ — milliseconds since epoch inside a string wrapper. Not ISO 8601. If your mock returns "2024-01-01", a V2 client can fail to parse it: SAP Cloud SDK for JavaScript throws an error for any Edm.DateTime value that is not in /Date(...)/ form.
Navigation properties. When your code calls $expand=to_BusinessPartnerAddress, the response must include nested entity collections inside each parent entity, each with their own __metadata and correct structure.
Deeper expansions like $expand=to_BusinessPartnerAddress/to_EmailAddress multiply the complexity at each level. SAP queries can expand two or three levels deep.
CSRF tokens. SAP requires an x-csrf-token: fetch handshake before any write operation. Your mock server needs to participate in this protocol or the client will fail before sending the actual request.
Entity naming mismatch. The URL uses A_BusinessPartner (the EntitySet), but SAP's __metadata.type says API_BUSINESS_PARTNER.A_BusinessPartnerType (the EntityType). These are defined separately in EDMX — EntitySet elements in the EntityContainer reference EntityType definitions in the schema. A mock has to resolve the set to its type before it knows which properties to return.
A mock server that returns static JSON handles none of this automatically. Here are five ways to deal with it, and their trade-offs.
Approach 1: Test Against the Real SAP System
No mocking: point the test environment at a shared SAP system and run the tests against it.
This works until:
- The VPN drops and your pipeline fails at 3am
- Another team mutates your test data mid-run
- SAP goes offline for a support package update
- You need parallel CI runs and SAP can't handle the concurrency
- A developer working remotely doesn't have VPN access
On a shared SAP test system, failures caused by SAP downtime or changed data are hard to predict and slow to diagnose. They are not dramatic crashes: the test that passed yesterday fails today because someone changed a business partner's category in the shared client.
Approach 2: Hand-Coded JSON Fixtures
Record a real response from SAP, save it as a JSON file, and serve it in tests.
{
"d": {
"results": [
{
"__metadata": {
"uri": "https://myhost/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner('1000001')",
"type": "API_BUSINESS_PARTNER.A_BusinessPartnerType"
},
"BusinessPartner": "1000001",
"BusinessPartnerFullName": "Acme Corp",
"BusinessPartnerCategory": "2",
"CreationDate": "/Date(1672531200000)/",
"to_BusinessPartnerAddress": { "results": [] }
}
]
}
}
Deterministic. Offline. Fast. Also fragile:
- Schema drift. SAP adds a new property in a support package. Your fixture doesn't have it. Deserialization succeeds, the property stays null in every test, and the code that reads it runs for the first time in production.
- Shallow coverage. You wrote fixtures for
A_BusinessPartnerandA_BusinessPartnerAddress. Your service integrates with 12 entity types. The other 10 have no test coverage. - Expanding complexity. Every new
$expandpath needs a new fixture file with manually nested entities.$expand=to_BusinessPartnerAddress,to_BusinessPartnerContactadds a second nested collection to every entity in the file.
Approach 3: WireMock or MockServer
A running HTTP server with request matching and response templates. Better than static files — you get URL path matching, query parameter handling, and response templating.
For SAP OData, a WireMock mapping looks like this:
{
"request": {
"method": "GET",
"urlPathPattern": "/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner.*"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"bodyFileName": "business-partners.json"
}
}
You still author or record every response body. For a service where you mock 20 entity sets:
- 20 entity sets = at least 20 mappings plus 20 response bodies
- Dozens of properties per type = hundreds of lines of JSON per response body
- Navigation properties = nested JSON that grows with each
$expanddepth level - Query variations = separate mappings or Handlebars templating for
$top,$filter,$inlinecount
WireMock does not read EDMX. It does not know that Edm.DateTime values are written as /Date(...)/ in V2 JSON, or which properties A_BusinessPartnerType declares. You encode SAP protocol details by hand in every response file, or record them from a live system with WireMock's record and snapshot features.
MockServer is also a general-purpose HTTP mock; its documentation describes no OData or EDMX support.
For a detailed comparison of WireMock and metadata-driven mocking for SAP OData, see MockLayer vs WireMock for SAP OData Testing.
Approach 4: Build Your Own Mock Server
The next step is to automate generation: parse the EDMX and generate responses in code. The EDMX specification is deeper than it looks:
- Entity type inheritance and abstract types
- Complex types nested within entity types
- Associations, AssociationSets, and ReferentialConstraints (V2) vs NavigationPropertyBinding (V4)
- Enum types (V4)
- SAP annotations:
sap:attributes and vocabulary-basedAnnotationsblocks
Each of these needs its own handling, and each gap shows up later as an edge case — an entity type with inheritance, a property with an unexpected annotation, a navigation property chain that doesn't resolve.
Readable test data adds another layer. A field named EmailAddress should contain an email address, not a random string. PostalCode should look like a postal code. Without property-name heuristics, the generated data matches the types but is hard to read when you debug.
The fundamental risk: you're now maintaining two products — your application and its mock server.
Approach 5: Metadata-Driven Mock Generation
This is the approach behind MockLayer. It starts from one observation: the structure is already in $metadata. The EDMX declares entity types, properties, data types, keys and navigation relationships: enough to generate responses with the right shape.
A mock server that reads this document can generate responses for any entity set in the service, without hand-written stubs.
MockLayer is a standalone HTTP server that:
- Fetches
$metadatafrom your SAP system, or takes an EDMX file you upload, and caches it in memory and on disk. After the configurable TTL expires (default 24 hours), the next request fetches$metadatafrom SAP again. If SAP is unreachable or returns an error at that point, the cached copy is served. The disk cache survives restarts, so SAP only needs to be reachable once per service. - Parses the EDMX to extract all entity schemas — entity types, navigation properties, complex types, and associations.
- Generates a value for each property from its EDM type. Property-name heuristics choose the kind of value:
*Email*fields get email addresses,*PostalCode*fields get postal codes, decimals named*Price*or*Amount*get monetary amounts.Edm.DateTimevalues are written as/Date(...)/in V2 responses and as ISO 8601 strings in V4 responses. - Wraps the data in the OData V2 envelope (
d,results,__metadata,__count) or, for/sap/opu/odata4/paths, the V4 envelope (value,@odata.count). - Handles CSRF tokens,
$expand(multi-level),$select,$orderby, and$inlinecount.$topsets how many entities MockLayer generates (3 by default).$filterconstraints are injected into data generation —$filter=BusinessPartnerCategory eq '2'produces entities where that property contains exactly'2', not post-filtered random data.
It uses Bogus for data generation and 11 entity-matching strategies to resolve EntitySet names to EntityType definitions — exact match, case-insensitive, plural/singular normalization, fuzzy Levenshtein matching, and more.
MockLayer listens on http://localhost:5000 by default. Your test code points there instead of the SAP host: same OData paths, same query options, same envelope. The places where MockLayer's responses differ from SAP's are listed under "What This Doesn't Solve" below.
In a CI/CD Pipeline
Here's a GitHub Actions workflow that runs SAP integration tests with no network dependency on SAP:
name: SAP Integration Tests
on: [push, pull_request]
# One license key covers one running MockLayer instance at a time.
# Runs of this workflow wait for each other instead of sharing the key.
concurrency:
group: sap-integration-tests
queue: max
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Start MockLayer
run: |
chmod +x ./MockLayer.Service
./MockLayer.Service &
# Wait until MockLayer answers and the license is valid
curl -sf -o /dev/null --retry 15 --retry-connrefused --retry-delay 1 \
http://localhost:5000/health
# Upload EDMX metadata — no SAP connection needed
curl -sf -o /dev/null -X POST \
-H "Content-Type: application/xml" \
--data-binary @test/edmx/API_BUSINESS_PARTNER.edmx \
'http://localhost:5000/sap/opu/odata/sap/API_BUSINESS_PARTNER/$metadata'
env:
MOCKLAYER_LICENSE: ${{ secrets.MOCKLAYER_LICENSE }}
RateLimit__PermitLimit: "0" # turn off the per-IP request limit
- name: Run tests
run: dotnet test --filter Category=SapIntegration
env:
SAP_BASE_URL: http://localhost:5000
The workflow expects two files in the repository: the Linux x64 build of MockLayer.Service (from the download page) at the root, and the EDMX file in test/edmx/. The EDMX file is an export from your SAP system — the same XML you get from GET /sap/opu/odata/sap/API_BUSINESS_PARTNER/$metadata. Update it when the service's metadata changes, for example after an SAP upgrade or when custom fields are added.
The health check waits until MockLayer answers. While the license key is missing or invalid, /health returns HTTP 503, so curl --retry gives up after 15 retries and the step fails before any test runs. The upload is a POST to the service's $metadata URL. --data-binary sends the file unchanged; -d would strip its line breaks.
One key, one running instance. Each license key covers one running MockLayer.Service instance at a time. A CI job that starts MockLayer counts as one instance while it runs, so jobs that run at the same time need one key each. The concurrency group makes runs of this workflow take turns, and queue: max keeps up to 100 later runs waiting instead of cancelling them. The group applies to one repository. If you split tests across parallel jobs or repositories, give each one its own key (Growth includes 3 keys, Enterprise 15), and do not use CI keys anywhere else.
Renewals. MockLayer reads MOCKLAYER_LICENSE at startup. Each renewal issues new keys, so update the secret when they arrive. An expired key keeps working through a grace period (7 days on Standard, 14 on Growth and Enterprise); after that, MockLayer answers every request except /health with HTTP 403.
Request limit. By default, MockLayer accepts 100 requests per minute per client IP and queues 10 more; further requests get HTTP 429 with Retry-After: 60. In CI, every request comes from localhost, so the workflow sets RateLimit__PermitLimit to 0, which turns the limit off.
If MockLayer can reach SAP (for example, on a self-hosted runner), you can skip the upload: set Sap__Host and the SAP credentials, and MockLayer fetches $metadata on the first request and again after the TTL. See the configuration reference for details.
Security. MockLayer serves plain HTTP without authentication. By default it listens on localhost:5000 only; if you bind it to a non-loopback address with ASPNETCORE_URLS or --urls, it logs a warning that other machines can reach it. Keep Sap__ValidateSsl at its default (true), use a read-only SAP technical user, and store the SAP credentials as CI secrets.
Test Code in Four Languages
Apart from credentials, the test code is the same whether it calls SAP or MockLayer: same OData paths, same query options, same V2 envelope. MockLayer needs no credentials from the test.
.NET
[Fact]
[Trait("Category", "SapIntegration")]
public async Task GetBusinessPartners_ReturnsValidODataResponse()
{
var client = new HttpClient
{
BaseAddress = new Uri(
Environment.GetEnvironmentVariable("SAP_BASE_URL")
?? "http://localhost:5000")
};
var response = await client.GetAsync(
"/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner"
+ "?$top=5&$expand=to_BusinessPartnerAddress");
response.EnsureSuccessStatusCode();
using var json = JsonDocument.Parse(
await response.Content.ReadAsStringAsync());
var results = json.RootElement
.GetProperty("d").GetProperty("results");
Assert.Equal(5, results.GetArrayLength());
foreach (var bp in results.EnumerateArray())
{
Assert.False(string.IsNullOrEmpty(
bp.GetProperty("BusinessPartner").GetString()));
Assert.True(
bp.TryGetProperty("to_BusinessPartnerAddress", out _));
}
}
The Trait attribute is what dotnet test --filter Category=SapIntegration in the workflow selects. Without it, the filter matches no tests and the step still succeeds.
Java
@Test
void getBusinessPartners_returnsValidODataResponse() throws Exception {
var baseUrl = System.getenv()
.getOrDefault("SAP_BASE_URL", "http://localhost:5000");
var response = HttpClient.newHttpClient().send(
HttpRequest.newBuilder()
.uri(URI.create(baseUrl
+ "/sap/opu/odata/sap/API_BUSINESS_PARTNER"
+ "/A_BusinessPartner?$top=5"))
.build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(200, response.statusCode());
var results = JsonParser.parseString(response.body())
.getAsJsonObject().getAsJsonObject("d")
.getAsJsonArray("results");
assertEquals(5, results.size());
assertNotNull(results.get(0).getAsJsonObject()
.get("BusinessPartner"));
}
Python
import os, requests
def test_get_business_partners():
base = os.environ.get("SAP_BASE_URL", "http://localhost:5000")
resp = requests.get(
f"{base}/sap/opu/odata/sap/API_BUSINESS_PARTNER"
"/A_BusinessPartner?$top=5&$expand=to_BusinessPartnerAddress")
assert resp.status_code == 200
results = resp.json()["d"]["results"]
assert len(results) == 5
assert all("BusinessPartner" in bp for bp in results)
assert all("to_BusinessPartnerAddress" in bp for bp in results)
Node.js
test('GET business partners returns valid OData', async () => {
const base = process.env.SAP_BASE_URL || 'http://localhost:5000';
const res = await fetch(
`${base}/sap/opu/odata/sap/API_BUSINESS_PARTNER`
+ `/A_BusinessPartner?$top=5`
);
expect(res.ok).toBe(true);
const { d: { results } } = await res.json();
expect(results).toHaveLength(5);
results.forEach(bp => {
expect(bp.BusinessPartner).toBeDefined();
expect(bp.__metadata.type).toContain('BusinessPartner');
});
});
The Node.js example uses Jest and the global fetch of Node.js 18 or later.
How the Five Approaches Compare
| Real SAP | JSON Fixtures | WireMock | Custom Server | MockLayer | |
|---|---|---|---|---|---|
| Reads EDMX | Is the source | No | No | Yes | Yes |
| Schema changes | Always current | Edit each fixture | Edit or re-record each stub | Re-read EDMX | Next metadata refresh, or upload a new EDMX file |
| OData envelope | Correct | Hand-coded | Hand-coded or recorded | Your code | Generated |
| Navigation props | Correct | Hand-coded | Hand-coded or recorded | Your code | Generated (differences below) |
| Needs SAP during tests | Yes | No | No | No | No |
| CSRF tokens | Yes | No | Hand-coded stub | Your code | Built in |
What This Doesn't Solve
MockLayer generates data from schema definitions. It covers one category of integration tests, not all of them:
- No state between requests. Each request generates fresh data. If your test creates a business partner via POST and reads it back via GET, MockLayer won't return the same entity. For CRUD sequence testing, you need a stateful mock or a real SAP sandbox.
- No business logic validation. It won't verify that a purchase order total matches its line items. The data follows the EDMX types; it is not semantically consistent.
- No
$batchor function imports. Bundled multi-operation requests and custom SAP function calls aren't supported. - No errors on demand. MockLayer has no option to return SAP error responses, delays, or connection faults. Use a tool such as WireMock for error paths.
- No facet enforcement or paging. Values follow EDMX data types, but
MaxLength,Precision, andScaleare not applied, and$skipis ignored. - Response details that differ from SAP:
__metadata.typeuses the entity set name (API_BUSINESS_PARTNER.A_BusinessPartner), not the entity type name that SAP returns (API_BUSINESS_PARTNER.A_BusinessPartnerType).- Navigation properties come back filled with generated entities, under a PascalCase name without the underscore (
ToBusinessPartnerAddress). SAP returns a__deferredlink instead.$expandadds the property under its EDMX name (to_BusinessPartnerAddress). - Other property names lose their underscores too:
JP_SupplierCapitalAmountCrcybecomesJPSupplierCapitalAmountCrcy, so a$selecton the EDMX name does not return it. - Entities added by
$expandcarry__metadata.typewithout the namespace (A_BusinessPartnerAddressType) and a generated key in__metadata.uri, and they leave out nullable properties that are not strings, such asEdm.DateTimeOffsetandEdm.Guid. - A read by key, such as
A_BusinessPartner('1000001'), puts the requested key in__metadata.uri, but the key property holds a generated value. - Writes return HTTP 200 with generated data; the OData V2 protocol defines 201 Created for a create (POST) and 204 No Content for an update (PUT). Writes must use JSON: a POST or PUT with an XML or text body is treated as an EDMX upload.
Edm.Decimalvalues are JSON numbers; SAP's V2 JSON sends them as strings.- V4 responses have no
@odata.context.
- Not an SAP replacement. For end-to-end testing of business processes that span multiple SAP transactions, you still need SAP.
What It Does Cover
Integration tests do more than validate data contracts. They check that your HTTP client is configured correctly (base URL, headers, serialization settings), that your deserialization pipeline handles a real payload, and that your application can reach a service over the network.
MockLayer runs as a real HTTP server on localhost:5000. Your test code makes a real HTTP request and parses a real response, so the network layer, HTTP client configuration, header construction, and response deserialization are exercised. MockLayer does not check or record the headers you send. Assertions on requests, error responses, and null values need another tool, such as WireMock.
What MockLayer removes from the equation is the dependency on SAP for the data behind that response. Instead of SAP generating the response from its database and business logic, MockLayer generates it from the same EDMX that SAP serves, with the differences listed above.
An integration test can ask two questions: "Does my code correctly handle what SAP sends back?" and "Does SAP's business logic produce the right result?" MockLayer addresses the first one offline, in CI, without stub files to maintain. The second one needs SAP.
MockLayer is a self-contained binary for Windows, Linux, and macOS: there is no .NET runtime to install. If you want to try it, there's a free 5-day trial that works without an SAP connection — upload an EDMX file and test against it locally.
WireMock is a trademark of its respective owner. MockLayer is an independent product, not affiliated with, sponsored or endorsed by the WireMock project. SAP trademarks: see the notice at the bottom of the page.