Class for which you will create unit test case.
class Authorization {
/* Observer so that mock object can work. */
public function attach(Curl $observer)
{
$this->observers = $observer;
}
/* Method for which we will create test */
public function postAuthorization($url, $method) {
return $this->observers->callAPI($url, $method);
}
}
Now we did not want any external interaction of our test code thus we need to create a mock object for callAPI function as this function is actually calling external url via curl.
class AuthorizationTest extends PHPUnit_Framework_TestCase {
protected $Authorization;
/**
* This method call every time before any method call.
*/
protected function setUp() {
$this->Authorization = new Authorization();
}
/**
* Test Login with invalid user credential
*/
function testFailedLogin() {
/*creating mock object of Curl class which is having callAPI function*/
$observer = $this->getMockBuilder('Curl')
->setMethods(array('callAPI'))
->getMock();
/* setting the result to call API. Thus by default whenver call api is called via this function it will return invalid user message*/
$observer->method('callAPI')
->will($this->returnValue('"Invalid user credentials"'));
/* attach the observer/mock object so that our return value is used */
$this->Authorization->attach($observer);
/* finally making an assertion*/
$this->assertEquals('"Invalid user credentials"', $this->Authorization->postAuthorization('/authorizations', 'POST'));
}
}
Below is the code for curl class(just a sample)
class Curl{
function callAPI($url, $method){
//sending curl req
}
}