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 uselaminas-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
?
You can try something like this:
//First you need to pass the client in your parameters
public function passes($attribute, $value $client): bool
...
//Then with phpunit it's possible to do
public function TestPasses()
{
//Replace myClasse with your real class wich contain the passes function
$myClasse = new myClasse();
$clientMock = $this
->getMockBuilder(SoapClient::class)
->disableOriginalConstructor()
->setMethods(['checkVat'])
->getMock();
$reponseMock $this
->getMockBuilder(/*Here it should be the classe returned by the checkVat function*/::class)
->disableOriginalConstructor()
->setMethods(['valid'])
->getMock();
$clientMock->expects($this->once())
->method('checkVat')
->with([ 'countryCode' => /*Put the value you want here*/, 'vatNumber' => /*Put the value you want here*/ ])
->willReturn($reponseMock);
$reponseMock->expects($this->once())
->method('valid')
->willReturn(true /*or false if you want*/);
$result = $myClasse->passes(/*Put the value you want here*/, /*Put the value you want here*/, $clientMock);
$this->assertEquals(true, $result);
}
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.