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

Mock the SellerMagnet API in C# Tests Without Spending Credits

Test the C# client that calls the SellerMagnet API without hitting it: point the C# quickstart's own base-URL constructor argument at a local System.Net.HttpListener fake, run the real SellerMagnetClient.cs / Models.cs / Retry.cs unchanged, and cover every billed, free and refunded status code with a 19-test suite that needs nothing beyond the .NET SDK.

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

Mock the SellerMagnet API in C# tests by pointing the C# quickstart's own constructor base-URL argument (already documented for SELLERMAGNET_API_BASE in FromEnv()) at a real local System.Net.HttpListener: FakeServer.cs scripts one response per request and SellerMagnetClient.cs, Models.cs and Retry.cs run completely unmodified against it over real HTTP on localhost. No credit is spent, no network call leaves the loopback interface, and nothing beyond the .NET SDK is required - not even a NuGet package.

Key Takeaways

  • The C# quickstart's own SellerMagnetClient has no injectable HttpMessageHandler; its constructor's base-URL argument, already named for SELLERMAGNET_API_BASE in FromEnv(), is the test seam.
  • Make the fake fail closed: a request before a test enqueues a response gets a 500 "no route installed" answer, never a silently plausible empty one.
  • A 429 is free and worth retrying; a 500 without Retry-After is refunded and worth one retry; a 502/503 is billed on every attempt, so cap the attempts.
  • Swap the client's own Delay property to a no-op per test instead of shrinking Retry.cs's backoff math, so the real retry decision runs without the suite sleeping through it.
  • A connection-refused error never reached the API (free, retried); a client-side timeout is billed up front and never retried, because the request may still be running server-side.

Why not just call the real API in a C# 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.

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 buyBox {} (nobody holds it)billednoFeatured() null, not a crash
offers buyBox.totalPrice float noisebillednoround once to 2 places
statistics minor-units pricebillednodivide by 100 (whole yen on amazon.co.jp)
404 product not foundbillednorecord it; never retry
401 bad keyfreenostop; never retry
429 concurrency capfreeyeswait Retry-After, then retry
500 internal errorrefundedyesretry once, then stop
502 / 503 upstreambilledyesretry up to the attempt cap
connection refusedfreeyesnever reached the API
client timeoutbillednomay still be running server-side

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

SellerMagnetClient's constructor already takes a base URL, the same seam the quickstart's own FromEnv() uses to read SELLERMAGNET_API_BASE "only for pointing the client at a local mock server in tests". FakeServer.cs turns that seam into something a test suite can script per scenario: Enqueue(status, body, ...) queues exactly the next response (FIFO, one entry per request), and an empty queue answers 500 "no route installed", so a test that forgets to script a response fails loudly instead of reaching for a plausible empty answer. LookupAsync, OffersAsync, StatisticsAsync and GetAsync (all from the C# quickstart) run exactly as they would in production.

Blueprint sequence diagram of a C# test faking the SellerMagnet API's HttpListener while the real client code runs unchanged
Only the fake server answers the request; SellerMagnetClient/Retry run unmodified.

FakeServer.cs - a real local HttpListener, scriptable per test, fails closed

// A real local HTTP server for tests: System.Net.HttpListener, no NuGet package needed.
// Fails closed: a request with no scripted response left gets a 500 "no route installed", never a false pass.
using System.Net;
using System.Text;

namespace SellerMagnet.Tests;

public sealed class FakeServer : IDisposable
{
    private readonly HttpListener listener = new();
    private readonly object sync = new();
    private readonly Queue<ScriptedResponse> queue = new();
    private readonly CancellationTokenSource cts = new();

    public string BaseUrl { get; }
    public int RequestCount { get; private set; }

    public FakeServer()
    {
        // Bind an ephemeral port by asking the OS for one, then reuse it for the listener prefix.
        int port;
        using (var probe = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0))
        {
            probe.Start();
            port = ((IPEndPoint)probe.LocalEndpoint).Port;
        }
        BaseUrl = $"http://127.0.0.1:{port}/";
        listener.Prefixes.Add(BaseUrl);
        listener.Start();
        _ = Task.Run(AcceptLoop);
    }

    /// <summary>Queue one scripted response. FIFO: the Nth request to reach this server gets the Nth entry.</summary>
    public void Enqueue(int status, string body, string? retryAfter = null, int delayMs = 0)
    {
        lock (sync)
        {
            queue.Enqueue(new ScriptedResponse(status, body, retryAfter, delayMs));
        }
    }

    private async Task AcceptLoop()
    {
        while (!cts.IsCancellationRequested)
        {
            HttpListenerContext ctx;
            try
            {
                ctx = await listener.GetContextAsync();
            }
            catch (Exception) when (cts.IsCancellationRequested || !listener.IsListening)
            {
                return;
            }
            _ = Task.Run(() => Handle(ctx));
        }
    }

    private async void Handle(HttpListenerContext ctx)
    {
        // async void: any exception that escapes here crashes the whole process, so this
        // whole body is one try/catch. A timeout test's client gives up mid-response and the
        // server (or the test's own Dispose) can tear the listener down while a write is pending.
        try
        {
            ScriptedResponse resp;
            lock (sync)
            {
                RequestCount++;
                // Fails closed: an un-scripted request is a test bug, not a silent 200.
                resp = queue.Count > 0
                    ? queue.Dequeue()
                    : new ScriptedResponse(500, "{\"success\":false,\"message\":\"no route installed\"}", null, 0);
            }
            if (resp.DelayMs > 0)
            {
                await Task.Delay(resp.DelayMs);
            }
            ctx.Response.StatusCode = resp.Status;
            if (resp.RetryAfter is not null)
            {
                ctx.Response.Headers.Add("Retry-After", resp.RetryAfter);
            }
            var bytes = Encoding.UTF8.GetBytes(resp.Body);
            ctx.Response.ContentType = "application/json";
            ctx.Response.ContentLength64 = bytes.Length;
            await ctx.Response.OutputStream.WriteAsync(bytes);
            ctx.Response.OutputStream.Close();
        }
        catch (Exception)
        {
            // The client gave up (a timeout test) or the test disposed the server already: nothing left to do.
        }
    }

    public void Dispose()
    {
        cts.Cancel();
        listener.Stop();
        listener.Close();
    }

    private readonly record struct ScriptedResponse(int Status, string Body, string? RetryAfter, int DelayMs);
}
Blueprint table of test scenarios against the SellerMagnet API's status codes, billing and the correct C# 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 NuGet package?

Each test opens its own FakeServer (using var server = new FakeServer();), so a leftover listener from a failed test can never leak into the next one. Client() builds a SellerMagnetClient pointed at that server with its Delay property swapped to a no-op, so the 429/500/502/503 scenarios exercise Retry.cs's real decision logic - which codes retry, which stop after one 500, which cap at 4 attempts - without the suite actually sleeping through an exponential backoff. A dedicated concurrency test drives Task.WhenAll across five lookups to prove SellerMagnetClient's own Interlocked-guarded Billed counter is race-safe, the same guarantee production callers already rely on.

Program.cs - the scenario suite, run for real below

// A reflection-free test runner: one Main, a list of async tests, no NuGet package needed.
// Each test gets its own FakeServer (System.Net.HttpListener) and points the UNCHANGED
// SellerMagnetClient/Models/Retry at it via the client's own documented base-URL test seam.
using SellerMagnet;
using SellerMagnet.Tests;

var tests = new List<(string Name, Func<Task> Run)>
{
    ("happy path lookup decodes a number price", HappyPathLookup),
    ("lookup N/A price becomes null, not 0", LookupNaPrice),
    ("offers buyBox {} deserializes to null SellerId, Featured() null", OffersEmptyBuyBox),
    ("offers buyBox.totalPrice is rounded once", OffersTotalPriceRounded),
    ("statistics MinorUnits divides by 100 outside Japan", StatisticsMinorUnits),
    ("statistics MinorUnits is whole yen on amazon.co.jp", StatisticsMinorUnitsJapan),
    ("statistics N/A buyBoxPrice becomes null", StatisticsNaPrice),
    ("404 is billed once and never retried", Status404NotRetried),
    ("401 is free and never retried", Status401NotRetried),
    ("429 is free and retried honouring Retry-After", Status429RetriedFree),
    ("500 without Retry-After is refunded and retried once", Status500RefundedRetriedOnce),
    ("a second consecutive 500 stops instead of looping", Status500SecondStops),
    ("502 is billed on every attempt up to the cap", Status502BilledEveryAttempt),
    ("503 is capped at the attempt limit", Status503CappedAtLimit),
    ("a non-JSON 200 body becomes an ApiException, not a crash", NonJsonBodyNoCrash),
    ("a malformed ASIN is skipped before any call is billed", MalformedAsinSkipped),
    ("a connection-refused error is free and retried", ConnectionRefusedFreeRetried),
    ("a timeout is billed once and never retried", TimeoutBilledNotRetried),
    ("5 concurrent lookups share Billed with no lost count", ConcurrentLookupsNoLostCount),
};

var passed = 0;
var failed = 0;
foreach (var (name, run) in tests)
{
    try
    {
        await run();
        Console.WriteLine($"PASS  {name}");
        passed++;
    }
    catch (Exception e)
    {
        Console.WriteLine($"FAIL  {name}: {e.Message}");
        failed++;
    }
}
Console.WriteLine($"{passed}/{passed + failed} passed");
return failed == 0 ? 0 : 1;

static void Assert(bool condition, string message)
{
    if (!condition)
    {
        throw new Exception(message);
    }
}

static SellerMagnetClient Client(FakeServer server, TimeSpan? timeout = null) =>
    new(server.BaseUrl, "test-key", timeout ?? TimeSpan.FromSeconds(5))
    {
        // Production uses Task.Delay; tests record the wait instead of actually sleeping.
        Delay = (_, _) => Task.CompletedTask,
    };

const string lookupOk = """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":444.99,"currencyCode":"USD"}}}}""";
const string lookupNa = """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":"N/A","currencyCode":"USD"}}}}""";
const string offersEmptyBuyBox = """{"success":true,"data":{"buyBox":{},"currency":{"code":"USD"},"offers":[]}}""";
const string offersUnrounded = """{"success":true,"data":{"buyBox":{"sellerId":"A3853PJW50SJG8","sellerName":"x","condition":"New","fulfillmentType":"FBA","priceWithoutShipping":398.08,"totalPrice":406.09000000000003,"inventory":30},"currency":{"code":"EUR"},"offers":[]}}""";
const string statsCents = """{"success":true,"data":{"buyBoxPrice":41800,"buyBoxFulfillment":"FBM"}}""";
const string statsJapan = """{"success":true,"data":{"buyBoxPrice":4180,"buyBoxFulfillment":"FBM"}}""";
const string statsNa = """{"success":true,"data":{"buyBoxPrice":"N/A","buyBoxFulfillment":null}}""";
const string err404 = """{"success":false,"message":"Invalid product"}""";
const string err401 = """{"success":false,"message":"Invalid or missing API key"}""";
const string err429 = """{"success":false,"message":"Max 40 concurrent requests per API key. Retry shortly."}""";
const string err500 = """{"success":false,"message":"An internal error occurred. Please try again shortly."}""";
const string err502 = """{"success":false,"message":"Bad gateway"}""";
const string err503 = """{"success":false,"message":"Service unavailable"}""";

static async Task HappyPathLookup()
{
    using var server = new FakeServer();
    server.Enqueue(200, lookupOk);
    using var client = Client(server);
    var info = await client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER");
    Assert(info.BuyBoxInfo?.Price == 444.99m, $"expected 444.99, got {info.BuyBoxInfo?.Price}");
    Assert(client.Billed == 1, $"expected 1 billed, got {client.Billed}");
}

static async Task LookupNaPrice()
{
    using var server = new FakeServer();
    server.Enqueue(200, lookupNa);
    using var client = Client(server);
    var info = await client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER");
    Assert(info.BuyBoxInfo?.Price is null, "\"N/A\" must become null, never 0 and never a JsonException");
}

static async Task OffersEmptyBuyBox()
{
    using var server = new FakeServer();
    server.Enqueue(200, offersEmptyBuyBox);
    using var client = Client(server);
    var offers = await client.OffersAsync("B0CL61F39H", "ATVPDKIKX0DER");
    Assert(offers.BuyBox?.SellerId is null, "buyBox: {} must deserialize to a null SellerId");
    Assert(offers.Featured() is null, "Featured() must be null when nobody holds the Buy Box");
}

static async Task OffersTotalPriceRounded()
{
    using var server = new FakeServer();
    server.Enqueue(200, offersUnrounded);
    using var client = Client(server);
    var offers = await client.OffersAsync("B0CL61F39H", "ATVPDKIKX0DER");
    Assert(offers.BuyBox?.TotalPrice == 406.09m, $"expected 406.09, got {offers.BuyBox?.TotalPrice}");
}

static async Task StatisticsMinorUnits()
{
    using var server = new FakeServer();
    server.Enqueue(200, statsCents);
    using var client = Client(server);
    var stats = await client.StatisticsAsync("B0CLTBHXWQ", "APJ6JRA9NG5V4");
    Assert(stats.BuyBoxPrice?.ToDecimal("APJ6JRA9NG5V4") == 418.00m, "41800 cents must divide to 418.00");
}

static async Task StatisticsMinorUnitsJapan()
{
    using var server = new FakeServer();
    server.Enqueue(200, statsJapan);
    using var client = Client(server);
    var stats = await client.StatisticsAsync("B0CL61F39H", "A1VC38T7YXB528");
    Assert(stats.BuyBoxPrice?.ToDecimal("A1VC38T7YXB528") == 4180m, "amazon.co.jp must read whole yen, not cents/100");
}

static async Task StatisticsNaPrice()
{
    using var server = new FakeServer();
    server.Enqueue(200, statsNa);
    using var client = Client(server);
    var stats = await client.StatisticsAsync("B0CL61F39H", "A2VIGQ35RCS4UG");
    Assert(stats.BuyBoxPrice is null, "\"N/A\" statistics price must become null");
}

static async Task Status404NotRetried()
{
    using var server = new FakeServer();
    server.Enqueue(404, err404);
    using var client = Client(server);
    await AssertThrowsApi(() => client.LookupAsync("B0NOTFOUND", "ATVPDKIKX0DER"), 404);
    Assert(server.RequestCount == 1, $"404 is an answer: expected 1 request, got {server.RequestCount}");
    Assert(client.Billed == 1, "404 must be billed once");
}

static async Task Status401NotRetried()
{
    using var server = new FakeServer();
    server.Enqueue(401, err401);
    using var client = Client(server);
    await AssertThrowsApi(() => client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER"), 401);
    Assert(server.RequestCount == 1, "401 (bad key) must never be retried");
    Assert(client.Billed == 0, "401 must be free");
}

static async Task Status429RetriedFree()
{
    using var server = new FakeServer();
    server.Enqueue(429, err429, retryAfter: "2");
    server.Enqueue(200, lookupOk);
    using var client = Client(server);
    var info = await client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER");
    Assert(info.BuyBoxInfo?.Price == 444.99m, "the retried call must succeed");
    Assert(server.RequestCount == 2, $"expected 2 requests (429 then retry), got {server.RequestCount}");
    Assert(client.Billed == 1, "the free 429 must not be billed; only the successful retry is");
}

static async Task Status500RefundedRetriedOnce()
{
    using var server = new FakeServer();
    server.Enqueue(500, err500); // no Retry-After: refunded
    server.Enqueue(200, lookupOk);
    using var client = Client(server);
    var info = await client.LookupAsync("B0CLTBHXWQ", "APJ6JRA9NG5V4");
    Assert(info.BuyBoxInfo?.Price == 444.99m, "the retried call must succeed");
    Assert(server.RequestCount == 2, "a 500 without Retry-After must be retried once");
    Assert(client.Billed == 1, "the refunded 500 must not be billed; only the successful retry is");
}

static async Task Status500SecondStops()
{
    using var server = new FakeServer();
    server.Enqueue(500, err500);
    server.Enqueue(500, err500);
    using var client = Client(server);
    await AssertThrowsApi(() => client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER"), 500);
    Assert(server.RequestCount == 2, $"a second consecutive 500 must stop, not loop to {server.RequestCount}");
}

static async Task Status502BilledEveryAttempt()
{
    using var server = new FakeServer();
    for (var i = 0; i < 4; i++)
    {
        server.Enqueue(502, err502);
    }
    using var client = Client(server);
    await AssertThrowsApi(() => client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER"), 502);
    Assert(server.RequestCount == 4, $"502 must be retried up to the 4-attempt cap, got {server.RequestCount}");
    Assert(client.Billed == 4, "every 502 attempt is billed");
}

static async Task Status503CappedAtLimit()
{
    using var server = new FakeServer();
    for (var i = 0; i < 4; i++)
    {
        server.Enqueue(503, err503);
    }
    using var client = Client(server);
    await AssertThrowsApi(() => client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER"), 503);
    Assert(server.RequestCount == 4, $"503 must stop at the 4-attempt cap, got {server.RequestCount}");
}

static async Task NonJsonBodyNoCrash()
{
    using var server = new FakeServer();
    server.Enqueue(429, "not json at all");
    server.Enqueue(200, lookupOk);
    using var client = Client(server);
    var info = await client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER");
    Assert(info.BuyBoxInfo?.Price == 444.99m, "a non-JSON error body must still retry, not crash");
}

static async Task MalformedAsinSkipped()
{
    using var server = new FakeServer(); // no response queued: a real call here fails the test
    Assert(!SellerMagnetClient.IsAsin("B0CL61F39"), "a 9-character string is not a valid ASIN");
    Assert(server.RequestCount == 0, "IsAsin must be checked before any network call, so nothing is billed");
}

static async Task ConnectionRefusedFreeRetried()
{
    // Nothing listens on port 1: an immediate, real connection-refused, not a scripted response.
    using var client = new SellerMagnetClient("http://127.0.0.1:1/", "test-key", TimeSpan.FromSeconds(5))
    {
        Delay = (_, _) => Task.CompletedTask,
    };
    await AssertThrows<HttpRequestException>(() => client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER"));
    Assert(client.Billed == 0, "a connection error never reached the API, so it must be free");
}

static async Task TimeoutBilledNotRetried()
{
    using var server = new FakeServer();
    server.Enqueue(200, lookupOk, delayMs: 400); // answers, but only after the client has given up
    using var client = Client(server, TimeSpan.FromMilliseconds(100));
    await AssertThrows<TaskCanceledException>(() => client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER"));
    Assert(client.Billed == 1, "a timeout is billed up front: the request may still be running server-side");
    Assert(server.RequestCount == 1, "a timeout must never be retried");
}

static async Task ConcurrentLookupsNoLostCount()
{
    using var server = new FakeServer();
    for (var i = 0; i < 5; i++)
    {
        server.Enqueue(200, lookupOk);
    }
    using var client = Client(server);
    await Task.WhenAll(Enumerable.Range(0, 5).Select(_ => client.LookupAsync("B0CL61F39H", "ATVPDKIKX0DER")));
    Assert(client.Billed == 5, $"Interlocked must keep all 5 concurrent calls, got {client.Billed}");
}

static async Task AssertThrowsApi(Func<Task> action, int expectedStatus)
{
    try
    {
        await action();
    }
    catch (ApiException e)
    {
        Assert(e.Status == expectedStatus, $"expected status {expectedStatus}, got {e.Status}");
        return;
    }
    throw new Exception($"expected an ApiException with status {expectedStatus}, none was thrown");
}

static async Task AssertThrows<TException>(Func<Task> action) where TException : Exception
{
    try
    {
        await action();
    }
    catch (TException)
    {
        return;
    }
    catch (Exception e)
    {
        throw new Exception($"expected {typeof(TException).Name}, got {e.GetType().Name}: {e.Message}");
    }
    throw new Exception($"expected {typeof(TException).Name}, none was thrown");
}

dotnet run output (unmodified run)

PASS  happy path lookup decodes a number price
PASS  lookup N/A price becomes null, not 0
PASS  offers buyBox {} deserializes to null SellerId, Featured() null
PASS  offers buyBox.totalPrice is rounded once
PASS  statistics MinorUnits divides by 100 outside Japan
PASS  statistics MinorUnits is whole yen on amazon.co.jp
PASS  statistics N/A buyBoxPrice becomes null
PASS  404 is billed once and never retried
PASS  401 is free and never retried
PASS  429 is free and retried honouring Retry-After
PASS  500 without Retry-After is refunded and retried once
PASS  a second consecutive 500 stops instead of looping
PASS  502 is billed on every attempt up to the cap
PASS  503 is capped at the attempt limit
PASS  a non-JSON 200 body becomes an ApiException, not a crash
PASS  a malformed ASIN is skipped before any call is billed
PASS  a connection-refused error is free and retried
PASS  a timeout is billed once and never retried
PASS  5 concurrent lookups share Billed with no lost count
19/19 passed

Never hand-write a fake of GetAsync or LookupAsync itself

A fake that reimplements LookupAsync or Retry.cs's own backoff tests the fake's own logic, not the real client. Fake one layer below your code - here, the HTTP listener 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 quickstart's own embedded HttpServer, and the PHP guide points Guzzle at a local php -S process; this guide points SellerMagnetClient's own base-URL constructor argument at a local HttpListener instead, since no in-process handler injection seam exists in the published quickstart. 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 C# 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 SellerMagnetClient.cs, Models.cs and Retry.cs from the C# quickstart run completely unmodified.

Why fake a local HttpListener instead of injecting a mock HttpMessageHandler?

HttpClient does support a custom HttpMessageHandler, but the C# quickstart's own SellerMagnetClient builds its HttpClient inside the constructor with no handler-injection parameter, to keep the quickstart itself to "no NuGet package needed". The constructor's own base-URL argument, already documented for SELLERMAGNET_API_BASE in FromEnv(), is the seam this suite uses instead: FakeServer.cs is a real local System.Net.HttpListener (also base class library, no NuGet) that the unmodified client talks actual HTTP to over localhost.

Why not use xUnit or NUnit for this suite?

Either works fine here too, but matching the quickstart's own "no NuGet package needed" pitch, Program.cs is a plain top-level statements file with a list of async test functions that reports PASS or FAIL per scenario, compiled and run with nothing but the .NET SDK already needed to build the quickstart itself.

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

This suite does not shrink Retry.cs's own backoff math, only its wait: the client's own Delay property (already exposed for exactly this, Task.Delay in production) is swapped to a no-op per test, so the real retry decision runs - which status codes retry, which stop after one 500, which cap at the 4-attempt limit - without the test suite actually sleeping through an exponential backoff.

Does the fake server handle concurrent requests safely?

Yes. A dedicated scenario runs five lookups at once with Task.WhenAll against one shared FakeServer and asserts the client's own Interlocked-guarded Billed counter reaches 5, with no count lost to a race, the same guarantee SellerMagnetClient already provides in production for parallel callers.

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

No. FakeServer defaults to a 500 "no route installed" answer when its response queue is empty, so a forgotten Enqueue() call fails the test loudly instead of quietly returning a plausible empty response.

Bottom line: point whatever base-URL seam your language's quickstart already exposes (here, the C# quickstart's own constructor argument) at a local HttpListener 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 well under a second - the client's own Delay property is swapped to a no-op, so the real retry decisions run without any real waiting - and spends zero credits, with nothing beyond the .NET SDK.

Related Articles

Continue exploring topics related to this article.

Back to Blog

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