У меня есть 2 вызова базы данных в одном методе, но из разных репозиториев, при первом вызове он работает нормально, но при втором вызове возникает ошибка, ожидающая другого репо. Вот тестовый класс:
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 просто обнулится.






Нашел ответ, мне нужно использовать метод willReturnOnConsecutiveCalls().
Так
$objectManager->expects($this->any())
->method('getRepository')
->willReturnOnConsecutiveCalls($currencyRepository,$regRepository);