我在一个方法中有2个数据库调用,但是来自不同的存储库,第一个调用可以正常工作,但是第二个调用会引发错误,它期望使用不同的存储库。 这是测试类:
GeneratorTest:
class Pet:
def __init__(self, name, eats):
self.name = name
self.eats = eats
# here i need to write my code.
cat = Cat(input("Cat name: "), input("Cat food: "))
dog = Dog(input("Dog name: "), input("Dog food: "))
dog.eat_cat(cat)
类生成:
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()
的仓库中只是空的。
答案 0 :(得分:0)
找到答案,我需要使用willReturnOnConsecutiveCalls()
方法。
所以
$objectManager->expects($this->any())
->method('getRepository')
->willReturnOnConsecutiveCalls($currencyRepository,$regRepository);