Mock the SellerMagnet API in Java tests by generalizing the Java quickstart's own embedded local server into a per-test scriptable fake: FakeServer.java runs a real com.sun.net.httpserver.HttpServer on a random port and lets each test install exactly the response it needs, while ApiClient.java, Lookup.java, Statistics.java, Retry.java and BatchLookup.java run completely unmodified against it through the constructor's own base-URL argument. No credit is spent, no network call leaves localhost, and nothing beyond the JDK is required - not even JUnit.
Key Takeaways
- The Java quickstart's own Main.java already points ApiClient at a local HttpServer instead of the live API; FakeServer.java only generalizes that same constructor seam into a per-test scriptable route.
- Make the fake fail closed: a request before a test installs its route should get a 500 "no route installed" answer, the same default the quickstart's own TestServer.java uses.
- A 429 is free and worth waiting out for real; a 500 is refunded and worth one retry; a 502/503 is billed on every attempt, so cap the attempts.
- This suite does not shrink Retry.java's backoff, so the 429/500/502 tests take real seconds - proof the actual wait and Retry-After handling work.
- No JUnit, no Maven: a 40-line reflection-based runner finds and runs every test method, matching the quickstart's own "standard library is enough" pitch.
Why not just call the real API in a Java test suite?
Every SellerMagnet API request is billed per the table below, whether it comes from production code or a test run. A CI run that fires on every push would spend credits on every build, a slow or flaky network turns a code bug into a failed pipeline, and a 429 or a second 500 in a row cannot be forced on demand against the live API at all. A fake server makes every status code in the table, including the rare ones, reproducible on every run.
| Scenario | Charged | Retry? | Client should |
|---|---|---|---|
| happy path lookup | billed | no | decode, 1 credit |
| lookup, no featured offer ("N/A") | billed | no | price stays null, never 0.0 |
| statistics, negative-cents history point | billed | no | point dropped, not treated as free |
| 404 product not found | billed | no | record it; never retry |
| free gate 400 (missing marketplaceId) | free | no | fix the request, no retry |
| 401 insufficient credits | free | no | stop; top up credits |
| 429 concurrency cap | free | yes | wait Retry-After, then retry |
| 500 internal error | refunded | yes | retry once, then stop |
| 502 / 503 upstream | billed | yes | retry up to the attempt cap |
How do I fake just the server, not my own code?
ApiClient's constructor already takes a base URL, the same seam the quickstart's own Main.java uses to point it at TestServer instead of the live API. FakeServer.java generalizes that embedded demo server into something a test suite can script per scenario: install(route) sets exactly the next response, and the default route (no install) answers 500 "no route installed", so a test that forgets to script a response fails loudly instead of silently reaching for a plausible empty answer. get(), Lookup(), Statistics.fromJson(), Retry.withRetry() and BatchLookup.run() (all from the Java quickstart) run exactly as they would in production.

FakeServer.java - generalizes the quickstart's own embedded server, fails closed
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* FakeServer generalizes the quickstart's own embedded TestServer.java (already shipped in
* Main.java) into a per-test scriptable fake: install(Route) scripts exactly one response for
* the next request(s), reset() restores a route that fails closed. ApiClient / Lookup /
* Statistics / Retry / BatchLookup / Json / ApiError run against it completely unchanged -
* the test seam is the constructor's own "base" argument, the same one the quickstart's own
* Main.java already uses to point ApiClient at a local server instead of the live API.
*/
final class FakeServer {
interface Route {
/** status, JSON body string, optional Retry-After seconds (0 = not sent) */
Response handle(String endpoint, Map<String, String> params);
}
record Response(int status, String body, int retryAfterSeconds) {
}
private static final Route BLOCKED = (endpoint, params) ->
new Response(500, "{\"success\":false,\"message\":\"no route installed for " + endpoint + "\"}", 0);
private final HttpServer server;
private final Map<String, AtomicInteger> calls = new ConcurrentHashMap<>();
private volatile Route route = BLOCKED;
FakeServer() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", this::handle);
server.setExecutor(null);
server.start();
}
String base() {
return "http://127.0.0.1:" + server.getAddress().getPort() + "/";
}
/** Scripts the next request(s). Call reset() when the test is done (prefer try/finally). */
void install(Route r) {
route = r;
}
void reset() {
route = BLOCKED;
calls.clear();
}
int callCount(String endpoint) {
AtomicInteger n = calls.get(endpoint);
return n == null ? 0 : n.get();
}
void stop() {
server.stop(0);
}
private void handle(HttpExchange ex) throws IOException {
String path = ex.getRequestURI().getPath().substring(1);
calls.computeIfAbsent(path, k -> new AtomicInteger()).incrementAndGet();
if (!"test-key".equals(ex.getRequestHeaders().getFirst("X-Api-Key"))) {
respond(ex, 401, "{\"success\":false,\"message\":\"Invalid or inactive API key.\"}", 0);
return;
}
Response r = route.handle(path, parseQuery(ex.getRequestURI().getQuery()));
respond(ex, r.status(), r.body(), r.retryAfterSeconds());
}
private static Map<String, String> parseQuery(String query) {
Map<String, String> out = new LinkedHashMap<>();
if (query == null || query.isEmpty()) return out;
for (String pair : query.split("&")) {
int eq = pair.indexOf('=');
if (eq < 0) continue;
try {
out.put(URLDecoder.decode(pair.substring(0, eq), "UTF-8"),
URLDecoder.decode(pair.substring(eq + 1), "UTF-8"));
} catch (Exception ignored) {
// decode failure: skip, never crash the fake over a malformed query string
}
}
return out;
}
private void respond(HttpExchange ex, int status, String body, int retryAfterSeconds) throws IOException {
if (retryAfterSeconds > 0) {
ex.getResponseHeaders().add("Retry-After", String.valueOf(retryAfterSeconds));
}
ex.getResponseHeaders().add("Content-Type", "application/json");
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(status, bytes.length);
ex.getResponseBody().write(bytes);
ex.close();
}
}

What does a full scenario suite look like, with no JUnit and no Maven?
Each test opens its own FakeServer on a random port and stops it in a finally block, so a leftover port from a failed test can never leak into the next one. The 429, 500 and 502 scenarios run Retry.java's real exponential backoff rather than shrinking it, so a pass is proof the actual wait and Retry-After handling work, at the cost of a few real seconds per test. A dedicated concurrency test drives BatchLookup.run()'s own thread pool against the fake to prove the fake's shared call-count map is safe under real concurrent requests, the same guarantee the quickstart's own embedded TestServer.java already relies on.
MockApiTests.java - the scenario suite, run for real below
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Scenario suite for ApiClient / Lookup / Statistics / Retry / BatchLookup / Json / ApiError -
* every one of those files is the unmodified quickstart source. Only FakeServer (new) stands
* in for the live API, through the constructor's own "base" argument.
*/
public final class MockApiTests {
private static final String ASIN = "B0CL61F39H";
private static final String MP = "ATVPDKIKX0DER";
private static Map<String, Object> product(Object price) {
return Map.of(
"productInfo", Map.of(
"asin", ASIN,
"title", "PlayStation5 console (slim)",
"link", "https://www.amazon.com/dp/" + ASIN,
"buyBoxInfo", Map.of(
"price", price,
"currencyCode", price.equals("N/A") ? "N/A" : "USD",
"sellerId", price.equals("N/A") ? "N/A" : "Amazon")));
}
private static String json(Map<String, Object> data) {
// hand-rolled: the quickstart's own Json.parse() only needs to read this back, not write it
return "{\"success\":true,\"data\":" + toJson(data) + "}";
}
@SuppressWarnings("unchecked")
private static String toJson(Object v) {
if (v instanceof Map<?, ?> m) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (var e : m.entrySet()) {
if (!first) sb.append(',');
first = false;
sb.append('"').append(e.getKey()).append("\":").append(toJson(e.getValue()));
}
return sb.append('}').toString();
}
if (v instanceof List<?> l) {
StringBuilder sb = new StringBuilder("[");
boolean first = true;
for (Object o : l) {
if (!first) sb.append(',');
first = false;
sb.append(toJson(o));
}
return sb.append(']').toString();
}
if (v instanceof String s) return "\"" + s + "\"";
return String.valueOf(v);
}
public void testHappyPathParsesTheRealResponseShape() throws Exception {
FakeServer server = new FakeServer();
try {
server.install((endpoint, params) -> new FakeServer.Response(200, json(product(444.99)), 0));
ApiClient client = new ApiClient(server.base(), "test-key");
ProductLookup p = ProductLookup.fromJson(client.get("amazon-product-lookup",
Map.of("asin", ASIN, "marketplaceId", MP)));
assertEquals(ASIN, p.asin());
assertEquals(444.99, p.buyBoxInfo().price());
assertEquals(1, server.callCount("amazon-product-lookup"));
} finally {
server.stop();
}
}
public void testNoFeaturedOfferPriceIsNotANumber() throws Exception {
FakeServer server = new FakeServer();
try {
server.install((endpoint, params) -> new FakeServer.Response(200, json(product("N/A")), 0));
ApiClient client = new ApiClient(server.base(), "test-key");
ProductLookup p = ProductLookup.fromJson(client.get("amazon-product-lookup",
Map.of("asin", ASIN, "marketplaceId", MP)));
if (p.buyBoxInfo().price() != null) {
throw new AssertionError("price = " + p.buyBoxInfo().price() + ", want null for \"N/A\"");
}
} finally {
server.stop();
}
}
public void testStatisticsPricesAreIntegerCentsNotDecimal() throws Exception {
FakeServer server = new FakeServer();
try {
String body = "{\"success\":true,\"data\":{\"asin\":\"" + ASIN + "\",\"stats\":{"
+ "\"buyBoxPriceHistory\":[[\"2026-10-01 00:00:00\",41800],[\"2026-10-03 00:00:00\",41299]]}}}";
server.install((endpoint, params) -> new FakeServer.Response(200, body, 0));
ApiClient client = new ApiClient(server.base(), "test-key");
Statistics stats = Statistics.fromJson(client.get("amazon-product-statistics",
Map.of("asin", ASIN, "marketplaceId", MP)));
assertEquals(2, stats.buyBoxPriceHistory().size());
assertEquals(418.0, stats.buyBoxPriceHistory().get(0).toDecimal());
} finally {
server.stop();
}
}
public void testNegativeCentsHistoryPointIsDropped() throws Exception {
FakeServer server = new FakeServer();
try {
String body = "{\"success\":true,\"data\":{\"asin\":\"" + ASIN + "\",\"stats\":{"
+ "\"buyBoxPriceHistory\":[[\"2026-10-01 00:00:00\",41800],"
+ "[\"2026-10-02 00:00:00\",-1],[\"2026-10-03 00:00:00\",41299]]}}}";
server.install((endpoint, params) -> new FakeServer.Response(200, body, 0));
ApiClient client = new ApiClient(server.base(), "test-key");
Statistics stats = Statistics.fromJson(client.get("amazon-product-statistics",
Map.of("asin", ASIN, "marketplaceId", MP)));
assertEquals(2, stats.buyBoxPriceHistory().size());
} finally {
server.stop();
}
}
public void test404IsBilledAndMustNotBeRetried() throws Exception {
FakeServer server = new FakeServer();
try {
server.install((endpoint, params) ->
new FakeServer.Response(404, "{\"success\":false,\"message\":\"Product not found.\"}", 0));
ApiClient client = new ApiClient(server.base(), "test-key");
try {
client.get("amazon-product-lookup", Map.of("asin", ASIN, "marketplaceId", MP));
throw new AssertionError("expected ApiError");
} catch (ApiError e) {
assertEquals(404, e.status);
}
assertEquals(1, server.callCount("amazon-product-lookup"));
} finally {
server.stop();
}
}
public void testFreeGate400MissingMarketplaceIdIsNotRetried() throws Exception {
FakeServer server = new FakeServer();
try {
server.install((endpoint, params) -> new FakeServer.Response(400,
"{\"success\":false,\"message\":\"marketplaceId is required.\"}", 0));
ApiClient client = new ApiClient(server.base(), "test-key");
try {
client.get("amazon-product-lookup", Map.of("asin", ASIN));
throw new AssertionError("expected ApiError");
} catch (ApiError e) {
assertEquals(400, e.status);
}
assertEquals(1, server.callCount("amazon-product-lookup"));
} finally {
server.stop();
}
}
public void test401InsufficientCreditsIsNotRetried() throws Exception {
FakeServer server = new FakeServer();
try {
ApiClient client = new ApiClient(server.base(), "wrong-key"); // FakeServer's own auth check fires
try {
client.get("amazon-product-lookup", Map.of("asin", ASIN, "marketplaceId", MP));
throw new AssertionError("expected ApiError");
} catch (ApiError e) {
assertEquals(401, e.status);
}
assertEquals(1, server.callCount("amazon-product-lookup"));
} finally {
server.stop();
}
}
public void test429ConcurrencyCapIsFreeAndRetriedWithARealWait() throws Exception {
FakeServer server = new FakeServer();
try {
AtomicBoolean first = new AtomicBoolean(true);
server.install((endpoint, params) -> {
if (first.compareAndSet(true, false)) {
return new FakeServer.Response(429,
"{\"success\":false,\"message\":\"Max 5 concurrent requests per API key.\"}", 1);
}
return new FakeServer.Response(200, "{\"success\":true,\"data\":{\"ok\":true}}", 0);
});
ApiClient client = new ApiClient(server.base(), "test-key");
long start = System.nanoTime();
Retry.withRetry(4, () -> client.get("amazon-product-lookup", Map.of("asin", ASIN, "marketplaceId", MP)));
double elapsed = (System.nanoTime() - start) / 1_000_000_000.0;
if (elapsed < 1.0) {
throw new AssertionError("elapsed=" + elapsed + "s, want >= 1s (real Retry-After wait, not shrunk)");
}
assertEquals(2, server.callCount("amazon-product-lookup"));
} finally {
server.stop();
}
}
public void test500IsRefundedAndRetriedExactlyOnce() throws Exception {
FakeServer server = new FakeServer();
try {
AtomicBoolean first = new AtomicBoolean(true);
server.install((endpoint, params) -> {
if (first.compareAndSet(true, false)) {
return new FakeServer.Response(500, "{\"success\":false,\"message\":\"internal error\"}", 0);
}
return new FakeServer.Response(200, "{\"success\":true,\"data\":{\"ok\":true}}", 0);
});
ApiClient client = new ApiClient(server.base(), "test-key");
Retry.withRetry(4, () -> client.get("amazon-product-lookup", Map.of("asin", ASIN, "marketplaceId", MP)));
assertEquals(2, server.callCount("amazon-product-lookup"));
} finally {
server.stop();
}
}
public void testASecondConsecutive500StopsInsteadOfLooping() throws Exception {
FakeServer server = new FakeServer();
try {
server.install((endpoint, params) ->
new FakeServer.Response(500, "{\"success\":false,\"message\":\"internal error\"}", 0));
ApiClient client = new ApiClient(server.base(), "test-key");
try {
Retry.withRetry(4, () -> client.get("amazon-product-lookup", Map.of("asin", ASIN, "marketplaceId", MP)));
throw new AssertionError("expected ApiError");
} catch (ApiError e) {
assertEquals(500, e.status);
}
assertEquals(2, server.callCount("amazon-product-lookup")); // first 500 + one retry, then stop
} finally {
server.stop();
}
}
public void test502IsBilledOnEveryAttemptUpToTheCap() throws Exception {
FakeServer server = new FakeServer();
try {
server.install((endpoint, params) ->
new FakeServer.Response(502, "{\"success\":false,\"message\":\"upstream error\"}", 0));
ApiClient client = new ApiClient(server.base(), "test-key");
try {
Retry.withRetry(4, () -> client.get("amazon-product-lookup", Map.of("asin", ASIN, "marketplaceId", MP)));
throw new AssertionError("expected ApiError");
} catch (ApiError e) {
assertEquals(502, e.status);
}
assertEquals(4, server.callCount("amazon-product-lookup")); // billed on all 4 attempts
} finally {
server.stop();
}
}
public void testMalformedAsinIsSkippedBeforeAnyCallIsBilled() throws Exception {
FakeServer server = new FakeServer();
try {
server.install((endpoint, params) -> new FakeServer.Response(200, json(product(444.99)), 0));
ApiClient client = new ApiClient(server.base(), "test-key");
List<BatchLookup.Row> rows = BatchLookup.run(client, MP, List.of("4.00638E+12"), 1);
assertEquals(1, rows.size());
if (rows.get(0).error() == null) {
throw new AssertionError("expected an error for a malformed ASIN");
}
assertEquals(0, server.callCount("amazon-product-lookup"));
} finally {
server.stop();
}
}
public void testFiveConcurrentLookupsAgainstTheSharedFakeServer() throws Exception {
FakeServer server = new FakeServer();
try {
server.install((endpoint, params) -> {
String asin = params.get("asin");
if ("B0UNKNOWN1".equals(asin)) {
return new FakeServer.Response(404, "{\"success\":false,\"message\":\"Product not found.\"}", 0);
}
return new FakeServer.Response(200, json(product(444.99)), 0);
});
ApiClient client = new ApiClient(server.base(), "test-key");
List<String> asins = List.of("B0CL61F39H", "B0AAAAAAA1", "B0AAAAAAA2", "B0UNKNOWN1", "B0AAAAAAA3");
List<BatchLookup.Row> rows = BatchLookup.run(client, MP, asins, 5);
assertEquals(5, rows.size());
assertEquals(5, server.callCount("amazon-product-lookup")); // every thread's call landed, none lost
long errors = rows.stream().filter(r -> r.error() != null).count();
assertEquals(1, (int) errors); // only B0UNKNOWN1
} finally {
server.stop();
}
}
public void testFakeServerFailsClosedWithoutInstall() throws Exception {
FakeServer server = new FakeServer();
try {
// no install() call: the default BLOCKED route must answer, never silently pass through
ApiClient client = new ApiClient(server.base(), "test-key");
try {
client.get("amazon-product-lookup", Map.of("asin", ASIN, "marketplaceId", MP));
throw new AssertionError("expected ApiError (fail closed)");
} catch (ApiError e) {
assertEquals(500, e.status);
if (!e.getMessage().contains("no route installed")) {
throw new AssertionError("message = " + e.getMessage());
}
}
} finally {
server.stop();
}
}
public void testHttpClientTimeoutHeaderIsSentAsAnHttpRequestTimeout() throws Exception {
FakeServer server = new FakeServer();
try {
// this is a smoke check that ApiClient's own 120s request timeout does not fire on a fast fake
server.install((endpoint, params) -> new FakeServer.Response(200, json(product(444.99)), 0));
ApiClient client = new ApiClient(server.base(), "test-key");
client.get("amazon-product-lookup", Map.of("asin", ASIN, "marketplaceId", MP));
assertEquals(1, server.callCount("amazon-product-lookup"));
} finally {
server.stop();
}
}
private static void assertEquals(Object expected, Object actual) {
if (expected == null ? actual != null : !expected.equals(actual)) {
throw new AssertionError("expected <" + expected + "> but was <" + actual + ">");
}
}
}
java -ea TestRunner output (unmodified run)
PASS test401InsufficientCreditsIsNotRetried (1.84s)
PASS test404IsBilledAndMustNotBeRetried (0.04s)
PASS test429ConcurrencyCapIsFreeAndRetriedWithARealWait (2.70s)
PASS test500IsRefundedAndRetriedExactlyOnce (3.08s)
PASS test502IsBilledOnEveryAttemptUpToTheCap (15.53s)
PASS testASecondConsecutive500StopsInsteadOfLooping (3.04s)
PASS testFakeServerFailsClosedWithoutInstall (0.05s)
PASS testFiveConcurrentLookupsAgainstTheSharedFakeServer (0.28s)
PASS testFreeGate400MissingMarketplaceIdIsNotRetried (0.10s)
PASS testHappyPathParsesTheRealResponseShape (0.06s)
PASS testHttpClientTimeoutHeaderIsSentAsAnHttpRequestTimeout (0.09s)
PASS testMalformedAsinIsSkippedBeforeAnyCallIsBilled (0.02s)
PASS testNegativeCentsHistoryPointIsDropped (0.07s)
PASS testNoFeaturedOfferPriceIsNotANumber (0.05s)
PASS testStatisticsPricesAreIntegerCentsNotDecimal (0.10s)
15 passed, 0 failed, 27.12s total
Never hand-write a fake of get() or Lookup() itself
A fake that reimplements Lookup() or Retry.withRetry() tests the fake's own logic, not the real client. Fake one layer below your code - here, the HTTP server it talks to - so a real bug in the decoding or retry logic still shows up as a failing test.
Does the same pattern work for other languages?
Yes, fake the one call the real code makes to the network, whichever shape that takes. The Python guide fakes requests.Session.get, the Go guide fakes http.RoundTripper, the PHP guide points Guzzle at a local php -S process, and the Node/Jest guide fakes globalThis.fetch; this guide generalizes the Java quickstart's own embedded HttpServer instead, since that seam already existed in the published code. The 429/Retry-After guide and the 502/503 retry guide are the production behaviour this suite checks against; keep all three in sync when the retry logic changes. Credit costs and the free trial are on the pricing page, and every endpoint's parameters are in the API documentation and code examples.
Frequently Asked Questions
Can Java tests call the real SellerMagnet API instead of faking it?
They can, but every call is billed the same as production traffic, so a CI run that fires on every push spends credits on every build, and a flaky network turns a code bug into a failed pipeline. A local fake server lets every billed, free and refunded status show up on demand while ApiClient.java, Lookup.java, Statistics.java, Retry.java and BatchLookup.java from the Java quickstart run completely unmodified.
Why fake a local HttpServer instead of a mocking library?
The Java quickstart's own Main.java already demonstrates its ApiClient against a local com.sun.net.httpserver.HttpServer (TestServer.java) instead of the live API, through the constructor's own base-URL argument. FakeServer.java generalizes that same idea into a per-test scriptable route, so the suite below needs nothing beyond the JDK: no JUnit, no Maven, no Mockito, matching the quickstart's own "standard library is enough" pitch.
Why not use JUnit for this suite?
JUnit works fine here too, but the Java quickstart's selling point is that the standard library is enough: no build tool, no jar. TestRunner.java keeps that promise for the test suite as well - about 40 lines of reflection that invoke every public void test method and report PASS or FAIL, compiled and run with nothing but javac and java.
How do I avoid real waits for a 429 or 500 retry test?
This suite does not shrink Retry.java's own backoff: a passing 429/500/502 test is proof the actual exponential wait and Retry-After handling work, not just that the code path was reached. Expect those tests to take a few real seconds each, and the 502 test (billed and retried to the attempt cap) to take the longest of the whole suite.
Does the fake server handle concurrent requests safely?
Yes. BatchLookup.java runs one thread per ASIN against a small fixed pool, and FakeServer tracks call counts in a ConcurrentHashMap of AtomicIntegers, the same pattern the quickstart's own embedded TestServer.java already uses. A concurrent scenario test runs five lookups at once and asserts every call landed exactly once, with no count lost to a race.
Should the fake answer anything if a test forgets to install a route?
No. FakeServer defaults to a route that answers 500 "no route installed", the same fail-closed default the quickstart's own TestServer.java already uses for an unmatched path. A forgotten install() then fails the test loudly instead of quietly returning a plausible empty response.
Bottom line: generalize whatever local test seam your language's quickstart already uses (here, the Java quickstart's own embedded HttpServer) into a per-test scriptable fake, run the real client code against scripted responses for every billed, free and refunded status, and make the fake fail closed so a forgotten scenario cannot send a real, billed request. The whole suite above runs in about 27 seconds - most of it real retry waits it refuses to fake - and spends zero credits, with nothing beyond the JDK.