Skip to content
Advertisement

Laravel how to mock SoapClient response for custom validation rule

Having a custom validation rule that uses the SoapClient I now need to mock it in tests.

    public function passes( $attribute, $value ): bool
    {
$value = str_replace( [ '.', ' ' ], '', $value );

        $country = strtoupper( substr( $value, 0, 2 ) );
        $vatNumber = substr( $value, 2 );
        $client = new SoapClient('https://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', [ 'soap_version' => SOAP_1_1 ]);
        $response = $client->checkVat( [ 'countryCode' => $country, 'vatNumber' => $vatNumber ] );

        return $response->valid;
    }

Used to use laminas-soap package but it doesn’t support PHP8. With laminas-soap it was possible to do

$this->mock( Client::class, function( $mock )
{
   $mock->shouldReceive( 'get' )->andReturn( new Response( true, 200 ) );
} );

But that doesn’t work with SoapClient::class.

Then tried from Phpunit, mocking SoapClient is problematic (mock magic methods) but also failed:

$soapClientMock = $this->getMockFromWsdl('soapApiDescription.wsdl');
$soapClientMock
    ->method('getAuthenticateServiceSettings')
    ->willReturn(true);

Tried from mock SoapClient response from local XML also failed:

$soapClient->expects($this->once())
        ->method('call')
        ->will(
            $this->returnValue(true)
        );

My question is how can I mock a soap response for a custom validation rule that uses SoapClient?

Advertisement

Answer

Found this laravel soap package that provides a easy to use Soap::fake.

Such as:

Soap::fake(function ($request) {
    return Soap::response('Hello World', 200);
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement