Hi
What is the correct way to do unit test a controller action?
class AController extends Controller
{
public function getAction()
{
$id = $this->request-getQuery('id');
... //codes block B (e.g. $id = $id * 2);
$a = A::findFirst($id);
... //codes block C
echo $a ? "Found" : "Not Found";
}
}
In this test I do not want to touch DB to do the query, so I mock the 'A' model. But I am not sure how to assign the mock model to the controller. something like this:
class AControllerTest extends UnitTestCase
{
protect function setUp()
{
parent::setUp();
// please assume I have setup relative services in below.
$this->di->set('request', ..);
$this->di->set('modelsManager', ..);
$this->di->set('dispatcher', ...)
}
public function testGetAction()
{
$a_mock = $this->getMockBuilder('A')
->setMethods(array('findFirst'))
->getMock();
$a_mock->expects($this->once())
->method('findFirst')
->will($this->returnValue(null));
// I am lost in here,
$controller = new AController();
$controller->getAction();
}
}
- I do not what to do with $a_mock, how to assign it to controller. so the line "$a = A::findFirst($id);" will return null.
- Even this will works, still it only test code block C. how do I test code bock B ?
Any help would be greatly appreciated, thanks in advance.