I cannot seem to wrap my head around mocking in phpunit. I have a test like this where I try to mock the execute method of my Curl Wrapper Class “CurlRequest”.
/** @test */
public function check_invalid_connection()
{
$mock = $this->getMockBuilder(CurlRequest::class)
->onlyMethods(['execute'])
->setConstructorArgs(["bla"])
->getMock();
$mock->method("execute")
->willThrowException(new Exception("Bla"));
$response = $this->json('POST', '/my-api-call');
}
Within this API call the following code is executed
$req = new CurlRequest("any-url");
$req->setOption(CURLOPT_USERPWD,"user-password");
$req->setOption(CURLOPT_CUSTOMREQUEST, 'MLSD');
$req->setOption(CURLOPT_USERPWD, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
$response = $req->execute();
die($response);
My expectation would be, that the mock leads to throwing an execption during the ->execute call. However, this is not happening.
I cannot seem to find a good example where someone trys not to directly call the functions of the $mock
they just created.
However, the constructor args seem to work as expected – when creating a new instance it will have “bla” as constructor arg.