Home / Blog / Mock the SellerMagnet API in Kotlin Tests Without Spending Credits

Mock the SellerMagnet API in Kotlin Tests Without Spending Credits

Test the Kotlin client that calls the SellerMagnet API without hitting it: a real local com.sun.net.httpserver.HttpServer stands in for the live API through Client.kt's own SELLERMAGNET_API_BASE constructor seam, left completely unmodified, with a 22-scenario suite covering every billed, free and refunded status code, a real client timeout and a verified-live finding that a refused connection is an uncaught exception, never an ApiError.

November 17, 2026
7 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing a Kotlin test run that fakes the SellerMagnet API behind a local HttpServer while the real HttpClient code runs unchanged

Mock the SellerMagnet API in Kotlin tests with a real local com.sun.net.httpserver.HttpServer (JDK standard library, no Ktor or OkHttp dependency) standing in for the live API: FakeServer.kt binds a free loopback port and lets each test enqueue exactly the responses it needs, while Client.kt and Models.kt from the Kotlin quickstart run completely unmodified against it through the constructor's own base parameter. No credit is spent, no request leaves localhost, and nothing beyond the Kotlin compiler, Gson and the JDK is required.

Key Takeaways

  • Client's constructor already reads SELLERMAGNET_API_BASE for its base parameter default; FakeServer.kt is a real HttpServer behind that exact seam, not a hand-written fake of Client itself.
  • Make the fake fail closed: a request with no scripted response left should get a 500 "no route installed" answer, never a plausible empty 200.
  • A 429 is free and worth waiting out for real; a 500 without Retry-After is refunded and worth one retry; a 502/503 is billed on every attempt, so cap the attempts.
  • Client's sleeper function parameter exists precisely so a test can record the requested wait instead of actually sleeping for it, without touching the retry loop's own backoff math.
  • Client.billedCalls is a plain, unsynchronized var, and Client.get() never catches a raw connection exception - verified directly, not assumed: give each worker thread its own Client, and expect a refused connection to propagate uncaught.

Why not just call the real API in a Kotlin 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, 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, with no network call leaving localhost.

Scenarios worth testing, and what the fake needs to script for each.
ScenarioChargedRetry?Client should
happy path lookupbillednodecode, 1 credit
lookup, no featured offer ("N/A")billednoprice stays null, never 0
offers, cheapest-new skip rulebillednoskip a 0.0 item price
404 product not foundbillednorecord it; never retry
free gate 400 (missing parameter)freenofix the request, no retry
endpoint's own 400 (bad ASIN)billednorecord it; never retry
401 insufficient creditsfreenostop; top up credits
429 concurrency capfreeyeswait Retry-After, then retry
500 internal errorrefundedyesretry once, then stop
502 / 503 upstreambilledyesretry up to the attempt cap
client timeoutbillednofirst request may still run
connection refusednot caughtnoan uncaught transport exception

How do I fake just the server, not my own code?

Client's constructor already takes a base parameter defaulting to System.getenv("SELLERMAGNET_API_BASE") - the same seam fromEnv() relies on to point at a local mock in tests. FakeServer.kt opens a real HttpServer on an OS-assigned free port, and enqueue(status, body, retryAfter) scripts exactly one response per expected request. A request that arrives with no scripted response left gets a 500 "no route installed" answer instead of a plausible empty 200, so a test that forgets to script a scenario fails loudly. lookup(), offers(), statistics() and get() (all from the Kotlin quickstart) run exactly as they would in production.

Blueprint sequence diagram of a Kotlin test faking the SellerMagnet API's local HttpServer while the real HttpClient code runs unchanged
Only the fake server answers the request; Client/Models run unmodified.

FakeServer.kt - a real local HttpServer behind the quickstart's own test seam, fails closed

package sellermagnet.tests

import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpServer
import java.net.InetSocketAddress
import java.nio.charset.StandardCharsets

/**
 * A real local HTTP server (com.sun.net.httpserver.HttpServer, JDK standard library, no Netty/
 * Ktor dependency), scripted per test. Drives the unmodified sellermagnet.Client/Models through
 * the client's own SELLERMAGNET_API_BASE seam (its constructor's "base" parameter already reads
 * that environment variable, documented for pointing at a local mock in tests), never a
 * hand-written fake of Client itself.
 */
data class FakeResponse(val status: Int, val body: String, val retryAfter: String? = null)

class FakeServer {
    private val server: HttpServer = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
    private val script = mutableListOf<FakeResponse>()
    private var index = 0
    private val requests = mutableListOf<String>()
    val requestCount: Int get() = synchronized(requests) { requests.size }

    init {
        server.createContext("/") { exchange -> handle(exchange) }
        server.executor = null
        server.start()
    }

    val base: String get() = "http://127.0.0.1:${server.address.port}"

    /** Scripts the next response. A request with no scripted response left fails closed: 500
     *  "no route installed", never a plausible empty 200. */
    fun enqueue(status: Int, body: String, retryAfter: String? = null): FakeServer {
        synchronized(script) { script.add(FakeResponse(status, body, retryAfter)) }
        return this
    }

    private fun handle(exchange: HttpExchange) {
        synchronized(requests) { requests.add(exchange.requestURI.toString()) }
        val entry = synchronized(script) {
            if (index < script.size) script[index++]
            else FakeResponse(500, "{\"success\":false,\"message\":\"no route installed\"}")
        }
        val bytes = entry.body.toByteArray(StandardCharsets.UTF_8)
        if (entry.retryAfter != null) {
            exchange.responseHeaders.add("Retry-After", entry.retryAfter)
        }
        exchange.responseHeaders.add("Content-Type", "application/json")
        exchange.sendResponseHeaders(entry.status, bytes.size.toLong())
        exchange.responseBody.use { it.write(bytes) }
    }

    fun stop() = server.stop(0)
}
Blueprint table of test scenarios against the SellerMagnet API's status codes, billing and the correct Kotlin client reaction
Each row needs its own scripted response; a happy-path test alone misses most of this.

What does a full scenario suite look like, with no test framework?

Each test opens its own FakeServer on a random port and stops it in a finally block, so a leftover listener from a failed test can never leak into the next one. The 429 and 500 scenarios pass a sleeper function that records the requested wait instead of sleeping for it, so the whole 22-test suite finishes in about two seconds while still proving the retry loop asked for the right wait and honoured Retry-After. Two scenarios deliberately probe the edges of Client's own concurrency and error-handling story instead of assuming it: a connection refused by a closed port propagates as a raw java.net.ConnectException, not an ApiError, since get() never catches it; and a shared Client's plain, unsynchronized billedCalls counter is only exercised with one Client per worker thread, the pattern that is actually safe.

MockApiTests.kt - the scenario suite, run for real below

package sellermagnet.tests

import sellermagnet.ApiError
import sellermagnet.Client
import java.net.ServerSocket
import java.net.http.HttpTimeoutException
import java.time.Duration
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess

/**
 * Scenario suite for sellermagnet.Client/Models - both files are the unmodified published
 * quickstart source. Only FakeServer (new) stands in for the live API, through the Client
 * constructor's own "base" parameter (the same SELLERMAGNET_API_BASE seam fromEnv() documents).
 * No JUnit, no Gradle test runner: a plain main() with one function per scenario, matching the
 * quickstart's own "no build tool beyond the base library + gson" pitch.
 */
private var ran = 0
private var failures = 0

private fun run(name: String, test: () -> Unit) {
    ran++
    try {
        test()
        println("PASS  $name")
    } catch (e: Throwable) {
        failures++
        println("FAIL  $name: $e")
    }
}

private fun assertTrue(cond: Boolean, message: String) {
    if (!cond) throw AssertionError("assertion failed: $message")
}

private fun client(server: FakeServer, waits: MutableList<Double>? = null, timeout: Duration = Duration.ofSeconds(120)) =
    Client(key = "test-key", base = server.base, sleeper = { s -> waits?.add(s) }, requestTimeout = timeout)

fun main() {
    // 1. happy path: lookup decodes a normal price
    run("happy path lookup decodes price") {
        val server = FakeServer()
        try {
            server.enqueue(200, "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":444.99,\"currencyCode\":\"USD\"}}}}")
            val c = client(server)
            val p = c.lookup("B0CL61F39H", "ATVPDKIKX0DER")
            assertTrue(p.buyBoxPrice == 444.99, "expected 444.99, got ${p.buyBoxPrice}")
            assertTrue(c.billed() == 1, "expected 1 billed, got ${c.billed()}")
        } finally { server.stop() }
    }

    // 2. "N/A" price becomes null, never 0.0
    run("\"N/A\" price converts to null, not 0") {
        val server = FakeServer()
        try {
            server.enqueue(200, "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":\"N/A\",\"currencyCode\":\"USD\"}}}}")
            val c = client(server)
            val p = c.lookup("B0CL61F39H", "ATVPDKIKX0DER")
            assertTrue(p.buyBoxPrice == null, "price should be null for \"N/A\"")
        } finally { server.stop() }
    }

    // 3. empty buyBox {} -> Offers.buyBox is null (size 0 object)
    run("empty buyBox {} decodes to a null buyBox") {
        val server = FakeServer()
        try {
            server.enqueue(200, "{\"success\":true,\"data\":{\"buyBox\":{},\"currency\":{\"code\":\"USD\"},\"offers\":[]}}")
            val c = client(server)
            val o = c.offers("B0CL61F39H", "ATVPDKIKX0DER")
            assertTrue(o.buyBox == null, "buyBox should be null when the API sends {}")
        } finally { server.stop() }
    }

    // 4. cheapestNew() skips an offer whose item price could not be read (0.0)
    run("cheapestNew skips an offer with unreadable price (0.0)") {
        val server = FakeServer()
        try {
            server.enqueue(200, "{\"success\":true,\"data\":{\"buyBox\":{},\"currency\":{\"code\":\"USD\"},\"offers\":[" +
                "{\"sellerId\":\"S1\",\"fulfillmentType\":\"FBM\",\"priceWithoutShipping\":0,\"totalPrice\":0,\"inventory\":1}," +
                "{\"sellerId\":\"S2\",\"fulfillmentType\":\"FBA\",\"priceWithoutShipping\":12.50,\"totalPrice\":15.00,\"inventory\":2}" +
                "]}}")
            val c = client(server)
            val o = c.offers("B0CL61F39H", "ATVPDKIKX0DER")
            val cheapest = o.cheapestNew()
            assertTrue(cheapest?.sellerId == "S2", "expected S2 (S1's unreadable price should be skipped), got ${cheapest?.sellerId}")
        } finally { server.stop() }
    }

    // 5a. statistics MinorUnits: amazon.co.jp is whole yen, never divided by 100
    run("statistics MinorUnits: whole yen on amazon.co.jp") {
        val server = FakeServer()
        try {
            server.enqueue(200, "{\"success\":true,\"data\":{\"buyBoxPrice\":4180,\"buyBoxFulfillment\":\"FBA\"}}")
            val c = client(server)
            val s = c.statistics("B0CL61F39H", "A1VC38T7YXB528")
            assertTrue(s.buyBoxPrice?.toDecimal("A1VC38T7YXB528") == 4180.0,
                "expected 4180 whole yen, got ${s.buyBoxPrice?.toDecimal("A1VC38T7YXB528")}")
        } finally { server.stop() }
    }

    // 5b. statistics MinorUnits: cents divided by 100 elsewhere
    run("statistics MinorUnits: cents divided by 100 elsewhere") {
        val server = FakeServer()
        try {
            server.enqueue(200, "{\"success\":true,\"data\":{\"buyBoxPrice\":41800,\"buyBoxFulfillment\":\"FBM\"}}")
            val c = client(server)
            val s = c.statistics("B0CLTBHXWQ", "APJ6JRA9NG5V4")
            assertTrue(s.buyBoxPrice?.toDecimal("APJ6JRA9NG5V4") == 418.0,
                "expected 418.0, got ${s.buyBoxPrice?.toDecimal("APJ6JRA9NG5V4")}")
        } finally { server.stop() }
    }

    // 6. 404 billed, not retried
    run("404 billed, not retried") {
        val server = FakeServer()
        try {
            server.enqueue(404, "{\"success\":false,\"message\":\"Invalid product ASIN\"}")
            val c = client(server)
            val e = runCatching { c.lookup("B0NOTFOUND", "ATVPDKIKX0DER") }.exceptionOrNull() as? ApiError
            assertTrue(e?.status == 404, "expected ApiError 404, got $e")
            assertTrue(server.requestCount == 1, "expected exactly 1 request, got ${server.requestCount}")
            assertTrue(c.billed() == 1, "404 is charged, expected 1 billed, got ${c.billed()}")
        } finally { server.stop() }
    }

    // 7. free gate 400 (missing marketplaceId) is free, not retried
    run("free gate 400 is free, not retried") {
        val server = FakeServer()
        try {
            server.enqueue(400, "{\"success\":false,\"message\":\"Missing required parameter: marketplaceId\"}")
            val c = client(server)
            val e = runCatching { c.statistics("B0CL61F39H", "A2VIGQ35RCS4UG") }.exceptionOrNull() as? ApiError
            assertTrue(e?.status == 400, "expected ApiError 400, got $e")
            assertTrue(server.requestCount == 1, "a free gate 400 must not be retried")
            assertTrue(c.billed() == 0, "expected 0 billed for a free gate 400, got ${c.billed()}")
        } finally { server.stop() }
    }

    // 8. an endpoint's own 400 (not a free-gate phrase) is billed, not retried
    run("endpoint's own 400 is billed, not retried") {
        val server = FakeServer()
        try {
            server.enqueue(400, "{\"success\":false,\"message\":\"Invalid product ASIN\"}")
            val c = client(server)
            val e = runCatching { c.statistics("B0CL61F39", "ATVPDKIKX0DER") }.exceptionOrNull() as? ApiError
            assertTrue(e?.status == 400, "expected ApiError 400, got $e")
            assertTrue(server.requestCount == 1, "an endpoint 400 must not be retried either")
            assertTrue(c.billed() == 1, "an endpoint's own 400 is charged, expected 1 billed, got ${c.billed()}")
        } finally { server.stop() }
    }

    // 9. 401 stops at once, not retried, not billed
    run("401 stops at once, not retried") {
        val server = FakeServer()
        try {
            server.enqueue(401, "{\"success\":false,\"message\":\"invalid API key\"}")
            val c = client(server)
            val e = runCatching { c.lookup("B0CL61F39H", "ATVPDKIKX0DER") }.exceptionOrNull() as? ApiError
            assertTrue(e?.status == 401, "expected ApiError 401, got $e")
            assertTrue(server.requestCount == 1, "401 must not be retried")
            assertTrue(c.billed() == 0, "401 is free, expected 0 billed, got ${c.billed()}")
        } finally { server.stop() }
    }

    // 10. 429 is free and retried, honouring Retry-After
    run("429 free, retried, honours Retry-After") {
        val server = FakeServer()
        try {
            server.enqueue(429, "{\"success\":false,\"message\":\"Max 40 concurrent requests per API key. Retry shortly.\"}", "2")
            server.enqueue(200, "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":444.99,\"currencyCode\":\"USD\"}}}}")
            val waits = mutableListOf<Double>()
            val c = client(server, waits)
            val p = c.lookup("B0CL61F39H", "ATVPDKIKX0DER")
            assertTrue(p.buyBoxPrice == 444.99, "should succeed on the retry")
            assertTrue(server.requestCount == 2, "expected 2 requests (1 free 429 + 1 retry), got ${server.requestCount}")
            assertTrue(c.billed() == 1, "429 is free, expected 1 billed, got ${c.billed()}")
            assertTrue(waits.size == 1 && waits[0] >= 2.0, "expected a wait >= 2s honouring Retry-After, got $waits")
        } finally { server.stop() }
    }

    // 11. a 500 without Retry-After is refunded and retried once, then succeeds
    run("500 without Retry-After refunded, retried once") {
        val server = FakeServer()
        try {
            server.enqueue(500, "{\"success\":false,\"message\":\"An internal error occurred. Please try again shortly.\"}")
            server.enqueue(200, "{\"success\":true,\"data\":{\"buyBoxPrice\":41800,\"buyBoxFulfillment\":\"FBM\"}}")
            val c = client(server, mutableListOf())
            val s = c.statistics("B0CLTBHXWQ", "APJ6JRA9NG5V4")
            assertTrue(s.buyBoxPrice != null, "should succeed on the retry")
            assertTrue(server.requestCount == 2, "expected 2 requests, got ${server.requestCount}")
            assertTrue(c.billed() == 1, "the first 500 is refunded, expected 1 billed total, got ${c.billed()}")
        } finally { server.stop() }
    }

    // 12. a second consecutive 500 is not looped a third time
    run("second consecutive 500 is not looped again") {
        val server = FakeServer()
        try {
            server.enqueue(500, "{\"success\":false,\"message\":\"An internal error occurred. Please try again shortly.\"}")
            server.enqueue(500, "{\"success\":false,\"message\":\"An internal error occurred. Please try again shortly.\"}")
            val c = client(server, mutableListOf())
            val e = runCatching { c.lookup("B0CL61F39H", "ATVPDKIKX0DER") }.exceptionOrNull() as? ApiError
            assertTrue(e?.status == 500, "expected ApiError 500, got $e")
            assertTrue(server.requestCount == 2, "expected exactly 2 requests (no third attempt), got ${server.requestCount}")
        } finally { server.stop() }
    }

    // 13. 502 is billed on every attempt, capped at 4
    run("502 billed every attempt, capped at 4") {
        val server = FakeServer()
        try {
            repeat(4) { server.enqueue(502, "{\"success\":false,\"message\":\"Bad gateway\"}") }
            val c = client(server, mutableListOf())
            val e = runCatching { c.lookup("B0CL61F39H", "ATVPDKIKX0DER") }.exceptionOrNull() as? ApiError
            assertTrue(e?.status == 502, "expected ApiError 502, got $e")
            assertTrue(server.requestCount == 4, "expected exactly 4 attempts, got ${server.requestCount}")
            assertTrue(c.billed() == 4, "502 is charged every attempt, expected 4 billed, got ${c.billed()}")
        } finally { server.stop() }
    }

    // 14. 503 capped at the same attempt limit
    run("503 capped at 4 attempts") {
        val server = FakeServer()
        try {
            repeat(4) { server.enqueue(503, "{\"success\":false,\"message\":\"Service unavailable\"}") }
            val c = client(server, mutableListOf())
            val e = runCatching { c.lookup("B0CL61F39H", "ATVPDKIKX0DER") }.exceptionOrNull() as? ApiError
            assertTrue(e?.status == 503, "expected ApiError 503, got $e")
            assertTrue(server.requestCount == 4, "expected exactly 4 attempts, got ${server.requestCount}")
        } finally { server.stop() }
    }

    // 15. a non-JSON body does not crash Client; it becomes an ApiError
    run("non-JSON body handled without a crash") {
        val server = FakeServer()
        try {
            server.enqueue(500, "<html>internal error</html>")
            server.enqueue(500, "<html>internal error</html>")
            val c = client(server, mutableListOf())
            val e = runCatching { c.lookup("B0CL61F39H", "ATVPDKIKX0DER") }.exceptionOrNull() as? ApiError
            assertTrue(e != null && e.message!!.contains("non-JSON body"), "expected a non-JSON body ApiError, got $e")
        } finally { server.stop() }
    }

    // 16. a malformed ASIN is rejected by isAsin before any call is billed
    run("malformed ASIN rejected before any call") {
        assertTrue(!Client.isAsin("B0CL61F39"), "9-char ASIN must not pass isAsin")
        assertTrue(!Client.isAsin("b0cl61f39h"), "lowercase ASIN must not pass isAsin")
        assertTrue(Client.isAsin("B0CL61F39H"), "a real 10-char upper ASIN must pass isAsin")
    }

    // 17. a client-side timeout is billed and reported, never retried
    run("client timeout is billed, reported, never retried") {
        val socket = ServerSocket(0) // bound but never accepted: the client's own request times out
        try {
            val c = Client(key = "test-key", base = "http://127.0.0.1:${socket.localPort}",
                sleeper = {}, requestTimeout = Duration.ofMillis(300))
            val e = runCatching { c.lookup("B0CL61F39H", "ATVPDKIKX0DER") }.exceptionOrNull() as? ApiError
            assertTrue(e != null && e.message!!.contains("client timeout"), "expected a client-timeout ApiError, got $e")
            assertTrue(c.billed() == 1, "a timeout is billed once it reaches the server, expected 1, got ${c.billed()}")
        } finally { socket.close() }
    }

    // 18. a connection refused by a closed port is an uncaught transport error, not an ApiError
    run("connection refused is an uncaught transport error, not billed") {
        val socket = ServerSocket(0)
        val deadPort = socket.localPort
        socket.close() // now refused, not just slow
        val c = Client(key = "test-key", base = "http://127.0.0.1:$deadPort", sleeper = {})
        var threw = false
        try {
            c.lookup("B0CL61F39H", "ATVPDKIKX0DER")
        } catch (e: ApiError) {
            throw AssertionError("expected a raw connection exception, not an ApiError: $e")
        } catch (e: Exception) {
            threw = true // java.net.ConnectException: Connection refused, uncaught by Client.get()
        }
        assertTrue(threw, "expected a connection exception to propagate")
        assertTrue(c.billed() == 0, "a connection that never reached the API must not be billed, got ${c.billed()}")
    }

    // 19. offers.inventory decodes as the add-to-cart cap, not the seller's real stock
    run("offers.inventory decodes as the cart cap, not stock") {
        val server = FakeServer()
        try {
            server.enqueue(200, "{\"success\":true,\"data\":{\"buyBox\":{\"sellerId\":\"A3853PJW50SJG8\",\"fulfillmentType\":\"FBA\",\"priceWithoutShipping\":399.99,\"totalPrice\":399.99,\"inventory\":30},\"currency\":{\"code\":\"USD\"},\"offers\":[]}}")
            val c = client(server)
            val o = c.offers("B0CL61F39H", "ATVPDKIKX0DER")
            assertTrue(o.buyBox?.inventory == 30, "expected 30, got ${o.buyBox?.inventory}")
        } finally { server.stop() }
    }

    // 20. five sequential lookups against one shared client and server accumulate Billed correctly
    //     (Client.billedCalls is a plain var, not synchronized - this suite deliberately runs this
    //     scenario single-threaded; see the FAQ on why a shared Client is not safe across threads).
    run("5 sequential lookups accumulate billed correctly") {
        val server = FakeServer()
        try {
            repeat(5) { server.enqueue(200, "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":1.0,\"currencyCode\":\"USD\"}}}}") }
            val c = client(server)
            repeat(5) { c.lookup("B0CL61F39H", "ATVPDKIKX0DER") }
            assertTrue(c.billed() == 5, "expected 5 billed from 5 sequential calls, got ${c.billed()}")
            assertTrue(server.requestCount == 5, "expected 5 requests, got ${server.requestCount}")
        } finally { server.stop() }
    }

    // 21. a concurrent run against a SEPARATE Client per thread (the documented-safe pattern,
    //     one Client per worker) correctly bills once per call with no cross-thread interference.
    run("concurrent run with one Client per thread bills correctly") {
        val server = FakeServer()
        try {
            repeat(5) { server.enqueue(200, "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":1.0,\"currencyCode\":\"USD\"}}}}") }
            val pool = Executors.newFixedThreadPool(5)
            val billedTotals = java.util.Collections.synchronizedList(mutableListOf<Int>())
            val tasks = (1..5).map {
                pool.submit {
                    val c = client(server) // one Client instance per thread: billedCalls never shared
                    c.lookup("B0CL61F39H", "ATVPDKIKX0DER")
                    billedTotals.add(c.billed())
                }
            }
            tasks.forEach { it.get(10, TimeUnit.SECONDS) }
            pool.shutdown()
            assertTrue(server.requestCount == 5, "expected 5 requests total, got ${server.requestCount}")
            assertTrue(billedTotals.all { it == 1 }, "each thread's own Client should report 1 billed, got $billedTotals")
        } finally { server.stop() }
    }

    println()
    println("${ran - failures}/$ran passed")
    if (failures > 0) exitProcess(1)
}

java -cp test.jar MockApiTestsKt output (unmodified run)

PASS  happy path lookup decodes price
PASS  "N/A" price converts to null, not 0
PASS  empty buyBox {} decodes to a null buyBox
PASS  cheapestNew skips an offer with unreadable price (0.0)
PASS  statistics MinorUnits: whole yen on amazon.co.jp
PASS  statistics MinorUnits: cents divided by 100 elsewhere
PASS  404 billed, not retried
PASS  free gate 400 is free, not retried
PASS  endpoint's own 400 is billed, not retried
PASS  401 stops at once, not retried
PASS  429 free, retried, honours Retry-After
PASS  500 without Retry-After refunded, retried once
PASS  second consecutive 500 is not looped again
PASS  502 billed every attempt, capped at 4
PASS  503 capped at 4 attempts
PASS  non-JSON body handled without a crash
PASS  malformed ASIN rejected before any call
PASS  client timeout is billed, reported, never retried
PASS  connection refused is an uncaught transport error, not billed
PASS  offers.inventory decodes as the cart cap, not stock
PASS  5 sequential lookups accumulate billed correctly
PASS  concurrent run with one Client per thread bills correctly

22/22 passed

Never hand-write a fake of Client.lookup() or Client.get() itself

A fake that reimplements lookup() or get() 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 deserialization 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 Java guide generalizes the same com.sun.net.httpserver.HttpServer this guide uses, and the C# quickstart points its HttpClient at a real local System.Net.HttpListener instead; this guide uses the Kotlin quickstart's own base-URL constructor parameter against the same JDK HttpServer the Java guide already uses, since Kotlin and Java share the same runtime. 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 Kotlin 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 429 or a second 500 in a row cannot be forced on demand against the live API. A local fake server lets every billed, free and refunded status show up on command while Client.kt and Models.kt from the Kotlin quickstart run completely unmodified.

Why fake a local HttpServer instead of mocking java.net.http.HttpClient?

The Kotlin quickstart's own Client already takes a base URL in its constructor, defaulting to the SELLERMAGNET_API_BASE environment variable - the same seam its fromEnv() factory uses to point at a local mock in tests. FakeServer.kt uses that exact seam with a real com.sun.net.httpserver.HttpServer on a random port (JDK standard library, the same class the Java mock-testing post generalizes), so the test exercises the real HttpClient over a real socket, not a mocked call.

Why not use JUnit or Kotest for this suite?

Either works fine here too, but the Kotlin quickstart's own selling point is a small dependency footprint: java.net.http.HttpClient from the JDK plus Gson for JSON, no Ktor, no OkHttp. The test runner in this post keeps that footprint: a plain main() with one function per scenario that prints PASS or FAIL, compiled and run with nothing but kotlinc, java and the same Gson jar the quickstart already needs.

How do I avoid real waits for a 429 or 500 retry test?

Client takes a sleeper function parameter (type (Double) -> Unit) in its constructor, defaulting to a real Thread.sleep. A test swaps in a function that records the requested wait instead, so the suite stays fast while still proving the retry loop asked for the right wait and honoured Retry-After when the response sent one.

Is Client safe to share across threads?

No, and this suite proves it rather than assuming it either way: billedCalls is a plain private var, incremented with billedCalls++, not an AtomicInteger or a synchronized block. The suite's concurrency scenario therefore gives each worker thread its own Client instance (the safe, documented-by-example pattern) instead of sharing one Client's counter across threads, which this client was never built to do.

What happens on a connection refused, like a closed port?

Client.get() only catches ApiError (an HTTP error status) and HttpTimeoutException. A java.net.ConnectException from a refused connection is neither, so it propagates straight out of lookup()/offers()/statistics() uncaught and unretried - a real, verified difference from languages whose client explicitly retries a connection error for free.

Should the fake answer anything if a test forgets to script a response?

No. FakeServer fails closed: a request with no scripted response left gets a 500 "no route installed" answer instead of a plausible empty 200. A forgotten enqueue() call then fails the test loudly instead of quietly passing on an unintended default.

Bottom line: use whatever local test seam your language's quickstart already exposes - here, Kotlin's own base constructor parameter against a real JDK HttpServer - to run the real client code against scripted responses for every billed, free and refunded status, verify rather than assume how it behaves at the edges (a refused connection, a shared counter), and make the fake fail closed so a forgotten scenario cannot send a real, billed request. The whole suite above runs in about two seconds and spends zero credits, with no Ktor and no OkHttp.

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime