编写服务的单元测试

时间:2018-12-05 10:30:48

标签: php unit-testing service phpunit repository

尝试PHP单元测试。我已阅读PHPUnit documentation并观看了Sandi Metz' video about unit testing,但在实际应用中很难应用所有这些内容。

我决定对我的CallReceiver类进行单元测试,该类接受一些参数并将实体传递到存储库以进行保存:

final class CallReceiver {

   private $CallRepository;

   public function __construct( CallRepository $CallRepository ) {

    $this->CallRepository = $CallRepository;
   }

   public function receive( string $uuid, string $Destination, string $Caller ) : void {

    $Call = Call::receive(
        CallId::createValidated( $uuid ),
        DestinationNumber::createValidated( $Destination ),
        $Caller
    );

    $this->CallRepository->save( $Call );
   }

}

根据Sandi的说法,我必须测试Call实体是否已发送到CallRepository(传出命令)。所以我想我必须同时模拟CallCallRepository

public function testReceive() {

    $CallRepository = $this->getMockBuilder(CallRepository::class)
        ->setMethods(['save'])
        ->getMock();

    $Call = $this->createMock(Call::class);

    $CallRepository->expects($this->once())
        ->method('save')
        ->with($this->equalTo($Call));

    $CallReceiver = new CallReceiver( $CallRepository );

    $CallReceiver->receive( '123', '456', '789' );

}

但这并不能真正起作用。如何为CallReveiver::receive方法编写有意义的测试?

0 个答案:

没有答案