Cheers @nakov, that makes perfect sense for my dumbed down example.
I made a mistake though, it doesn't really reflect my actual problem well enough so here is another more detailed example.
I am writing test coverage for the route /sum. I want to cover a successful request where the sum is returned and I also want to cover when there is an exception (some error with the third party service Acuity). To do this I wanted to fake the sum function and return either an expected result or an exception.
Here is the example route:
Route::get('/sum', function () {
try {
$calculator = new App\Calculator();
return $calculator->sum();
} catch (Exception $exception) {
return $exception->getMessage();
}
});
My example class:
<?php
namespace App;
use App\Acuity\AcuitySchedulingApi;
class Calculator
{
private int $a = 1;
private int $b = 2;
public function sum(): int
{
/*********************************************************/
// Calls a third party service API which I don't want called
$acuity = new \AcuityScheduling([
'userId' => config('services.acuity.user'),
'apiKey' => config('services.acuity.secret'),
]);
$response = $acuity->request('/me');
// Dumping response to show API is called
dump($response);
/*********************************************************/
// Dummy data for this example
return $this->a + $this->b;
}
}
Here is the example test
public function testCalculatorSum()
{
$this->mock(Calculator::class, function (MockInterface $mock) {
$mock->shouldReceive('sum')
->once()
->andReturn(5);
});
$response = $this->get('/sum');
$this->assertEquals(5, $response->content());
}
Example test results:
array:42 [
"expires" => null
"id" => 2xxxxxx
...
"hasExpired" => false
]
Failed asserting that '3' matches expected 5.
Expected :5
Actual :3
I thought mocking the Calculator function sum would mean the Acuity API wouldn't be called but my mocked class is not called, instead the route /sum is instantiating its own Calculator class and calling the API as it would normally.
How can I mock the sum function? Or should I be testing the code differently? Acuity uses cURL rather than HTTP Client so I don't know how I would go about mocking it directly so I thought mocking sum would be the easiest. Any thoughts?