laraveltesting

Laravel faking Http responses with different data in one test


I am struggeling Http::fake(). I have a test where I have to change the response body after the first faked API call, but it seems this is not possible.

Http::fake([
            'https://my.apicall.com/api/v1/Invoice/Factory/saveInvoice' => Http::response($invoiceBody, 201),
        ]);

// some code executed

Http::fake([
            'https://my.apicall.com/api/v1/Invoice/Factory/saveInvoice' => Http::response($invoiceBody2, 201),
        ]);

// more code executed

the second Http::fake() gets ignored, i receive the first body. Any ideas?


Solution

  • You can use sequence instead of define fake response multiple times. Something like this

    Http::fake([
        'https://my.apicall.com/api/v1/Invoice/Factory/saveInvoice' => Http::sequence()
            ->push($invoiceBody, 201)
            ->push($invoiceBody2, 201),
    ]);
    
    // Your code