【问题标题】:Symfony Unit Test mock 2 repositoriesSymfony 单元测试模拟 2 存储库
【发布时间】:2018-07-18 06:20:24
【问题描述】:

我在一个方法中有 2 个数据库调用,但来自不同的存储库,第一次调用它工作正常,但第二次调用抛出错误,它期待不同的 repo。 这是测试类:

GeneratorTest:

class GeneratorTest extends TestCase
{
   function testGenerate()
   {
       $currencyShortCode  = new CurrencyShortCode();
       $currencyShortCode->setCurrency('USD');
       $currencyShortCode->setCurrencyShort('US');

       $regulator =  new Countries();
       $regulator->setCountry('USA');
       $regulator->setCode('US');

       $currencyRepository = $this->createMock(CurrencyRepo::class);
       $currencyRepository->expects($this->any())
          ->method('getShortCode')
          ->willReturn($currencyShortCode);

       $regRepository = $this->createMock(RegulatorRepo::class);
       $regRepository->expects($this->any())
           ->method('getInitial')
           ->willReturn($regulator);

        $objectManager = $this->createMock(ManagerRegistry::class);

        $objectManager->expects($this->any())
           ->method('getManager')
           ->willReturn($objectManager);

       $objectManager->expects($this->any())
          ->method('getRepository')
          ->with(CurrencyShortCode::class)
          ->willReturn($currencyRepository);

       $objectManager->expects($this->any())
          ->method('getRepository')
          ->with(RegulatorCountries::class)
          ->willReturn($regRepository);

       $generator = new Generate($objectManager);
       $generator->generate();
    }
}

类生成:

class Generate
 {
    private $repo;
 public function __construct(ManagerRegistry $managerRegistry)
   {
        $this->repo = $managerRegistry->getManager();
   }

 public function generate()
   {         
    $data= $this->repo->getRepository(CurrencyShortCode::class)->getShortCode();
    $data1 = $this->repo->getRepository(RegulatorCountries::class)->getInitial();

   }

 }

我想问题出在这几行:

$objectManager->expects($this->any())
           ->method('getRepository')
            ->with(CurrencyShortCode::class)
           ->willReturn($currencyRepository);

        $objectManager->expects($this->any())
            ->method('getRepository')
            ->with(RegulatorCountries::class)
            ->willReturn($regRepository);

如何判断第一次调用Generator 类中的存储库时使用CurrencyShortCode::class 存储库,第二次调用使用RegulatorCountries::class,在我的情况下,第二次调用它仍然使用第一个存储库CurrencyShortCode::class .我尝试使用$this->at(0),但仍然无法正常工作。如果我在第二次调用存储库时删除->with() 方法,$data1 只是空。

【问题讨论】:

    标签: php unit-testing symfony phpunit


    【解决方案1】:

    找到答案,我需要使用willReturnOnConsecutiveCalls() 方法。 所以

    $objectManager->expects($this->any())
                ->method('getRepository')
                ->willReturnOnConsecutiveCalls($currencyRepository,$regRepository);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-01
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多