I have created a class with a function that makes a request to an external site using file_get_contents()
class MyClass {
public function emailExternal($email, $url){
$url = $url;
$data = array('email' => $email);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = $this->makeExternalRequest($url, $context);
return $result;
}
private function makeExternalRequest($url, $context){
return json_decode(file_get_contents($url, false, $context), true);
}
}
I have removed some of the function so i am only exposing what is required to understand my issue (This is why the function doesn't really do much)
I need to test the emailExternal function but need to mock the return of the makeExternalRequest function. Just so i can simulate a successful/not-successful response.
This is my attemot so far:
public function testEmailFromExternalSiteInvalidEmail(){
$results = [
'message' => 'test'
];
$stub = $this->getMockBuilder('MyClass')
->setMethods(['makeExternalRequest'])
->getMock();
$stub->expects($this->once())
->method('makeExternalRequest')
->withAnyParameters()
->will($this->returnValue($results));
$stub->emailExternal(['email' => 'test@test.co.uk'], 'http://test.com');
}
The above works fine if the makeExternalRequest function is public or protected but no longer works whilst it is private. Its required i keep this function private but is also required that i test. Does anyone know of anything i could do?