Code Organization
The feature we will be using with Prophecy is the ability to define when the return values are for a given method call (for specific arguments). To make this work for network calls, we want a class that encapsulates these calls, and little more. We want a method to accept the parameters that will be sent to the service, and return the expected result.
Let's use a login method call as an example. And say that we have a NetworkService class that implements an interface that looks like this.
interface NetworkServiceInterface {
public function login($user, $password);
}
In our test class, we will create a method that handles the creation of these mock requests. The snippet below assumes you are implementing KernelTestBase to have access to the prophesize() method.
protected function setUpNetworkRequests() {
$prophecy = $this->prophesize(NetworkServiceInterface::class);
$prophecy->login('mbopp@rapiddg.com', 'test')->willReturn([
"code" => 201,
"result" => [
"UserId" => "7b2ff57a-b64e-4c9c-8843-18df60ca5a16",
"Token" => "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODYzNjg1MDMsInR5cGUiOiJHYXJyaXNvbkRlbnRhbFdlYiIsInVzZXJJZCI6IjdiMmZmNTdhLWI2NGUtNGM5Yy04ODQzLTE4ZGY2MGNhNWExNiIsInJvbGVOYW1lcyI6W10sInRva2VuVHlwZSI6MH0.9XCvFSmxaml7wbLF6jX0QS49qoRGjCsQwwBg2Xpc-nw",
"ExpiredOn" => "2020-04-08T17:55:03Z",
],
]);
$prophecy->login('mbopp@rapiddg.com', 'badpass')->willReturn([
"code" => 401,
"result" => [
"RetryLeft" => 4,
"Message" => "Invalid password for given identifier: mbopp@rapiddg.com. Number of retry left: 4",
"Code" => 1004,
],
]);
$prophecy->login('mbopp@not.com', 'test')->willReturn([
"code" => 404,
"result" => [
"Message" => "No user found with the given identifier: mbopp@not.com",
"Code" => 1001,
],
]);
return $prophecy->reveal();
}
The reveal() method of a Prophecy object turns it into the reflected class, like your code will expect. In this case, NetworkServiceInterface.