首页 > 解决方案 > 为服务编写单元测试

问题描述

尝试 PHP 单元测试。我已经阅读了PHPUnit 文档并观看了Sandi Metz 的有关单元测试的视频,但是我很难将所有这些应用到现实世界的场景中。

我决定对我的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方法编写一个有意义的测试?

标签: phpunit-testingservicephpunitrepository

解决方案


推荐阅读