简体   繁体   中英

Unit Testing services in Symfony2

I am new in application testing and in Symfony2, so I have a one question. For exaple I have a few sevices, one send mails( $this->mailer->send($message) ) and the second do some things with entity instance and then return a instance prepeared for persist, so in first case I need to check only assertTrue() (sended or not)? But what need to check the second? Can somebody help me?

Actually, this is a pretty broad question. One example of what I usually do when testing services that "modify" entities might be as follows:

Service Adder updates the state of an entity: based on another entity adds value to the entity and sets correct values prior to persist.

// src/Acme/DemoBundle/Tests/Service/AdderTest.php
namespace Acme\DemoBundle\Tests\Service;

use Acme\DemoBundle\Service\Adder;
use Acme\DemoBundle\Entity\One;
use Acme\DemoBundle\Entity\Two;

class AdderTest extends \PHPUnit_Framework_TestCase
{
    public function testAdd()
    {
        $add = new Adder();
        $ent1 = new One();
        $ent2 = new Two();

        $ent2->setValue(1);
        $add->setOne($ent1);
        $add->setTwo($ent2);

        $add->updateEntity();// $ent1->setValue($ent2->getValue()+1);

        $this->assertEquals(2, $ent1->getValue());// Expected state of $ent1
    }
}

Of course, it usually gets more complex but at least it can give you an idea of how to start (use the service to update the state of an entity and check that the new state of the entity is the one expected).

Hope it helps.

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