简体   繁体   中英

How to test services with PHPunit and Zend Framework 2

I have completed testing my controllers, and have mocked the methods in the services. I would now like to test the service methods. I have searched online but have not come across good articles. If there are any pointers, links etc.. for PHPunit testing services, in zend framework 2 would be ideal.

So far I have tried this:

public function testFindInternById()
{
    $intern = new \Intern\Entity\InternEntity();
    $intern->setId(123);
    $intern->setFirstName('David');
    $intern->setLastName('Random');
    $intern->setTertiaryInstitute('UCT');
    $intern->setEducationalFeedback('educationalFeedback');
    $intern->setStartDate('2015-05-01');
    $intern->setEndDate('2015-05-02');
    $intern->setEmail('david.random@effcomm.com');
    $intern->setCv('4f7ae9d402168b5949cfda6deeee6620emir4.pdf');
    $intern->setCvRating(0);
    $intern->setProfilePicture('random.jpg');
    $intern->setInternshipRole('QA');
    $intern->setWebsite('www.random.com');
    $intern->setContactNumber('(123)-213-3434');
    $intern->setCurrentLocation('Mars');

    $emMock = $this->getMock('EntityManager', array('getRepository', 'getClassMetadata', 'persist', 'flush', 'find'), array(), '', false);
    $emMock->expects($this->any())
            ->method('find')
            ->will($this->returnValue($intern));

    $internService = new \Intern\Service\Intern\InternService();
    $internService->removeIntern($intern);     
}

Some methods have no returns so I would just be testing if they are being accessed, in code coverage terms 'I wanna see the green baby'. So ye any tips would be much appreciated.

I just wanted to mention that it doesn't matter if you have ZF2 or any other framework or custom code. You are not testing the framework but your code.

Lets say you want to test that you are able to remove an intern. Than your service need to have a dependency on repository.

$internId = 1;

$repositoryMock = $this->getMockBuilder('\RepositoryClass')->disableOriginalConstructor()->setMethods(array('findOnyById', 'delete'));

$repositoryMock->expects($this->once())->method('findOnyById')->with($internId)->willReturn($internMock);
$repositoryMock->expects($this->once())->method('delete')->with($internId);

$internMock = $this->getMockBuilder('\Intern\Entity\InternEntity')->disableOriginalConstructor()->getMock();

$internService = new \Intern\Service\Intern\InternService($repositoryMock);
$internService->removeIntern($internId);

The only important thing is that your service calls all the necessary methods with expected parameters. I think this is a good direction.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM