如何使用實體管理器測試我的工廠?我有一個錯誤,因爲我需要讓我的容器返回一個從doctrine
創建的類的實例(我甚至不知道返回的是什麼)。如何對依賴關係的工廠進行單元測試
如何創建一個測試,我可以通過?
// factory i want to test
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$googleAppOption = $container->get(GoogleAppOptions::class);
$em = $container->get('doctrine.entity_manager.orm_default');
return new GoogleTokenHandler($googleAppOption, new GoogleTokenClient(), $em);
}
//test function
public function testReturnsTokenHandlerInstance()
{
$googleOptionsFactory = new GoogleOptionsFactory();
$googleOptions = $googleOptionsFactory($this->container->reveal(), null);
$this->container->get(GoogleAppOptions::class)->willReturn($googleOptions);
$googleTokenHandlerFactory = new GoogleTokenHandlerFactory($this->container);
$tokenHandler = $googleTokenHandlerFactory($this->container->reveal(), null);
$this->assertInstanceof(GoogleTokenHandler::class, $tokenHandler);
}
但是這意味着我需要一個工廠來創建我的工廠? –
或者我應該使用我的控制器中的服務定位器來創建我的TokenHanlderFactory? –
我沒有看到哪個工廠會創建工廠,但一般來說 - 如果涉及到某種動態性 - 有一個「FactoryFactory」會很有用,而在Java代碼庫中它有點常見(當某些狀態在請求之間保持時) 。在你的控制器中,你可以使用容器來獲得工廠,或者用一些DI容器直接獲得TokenHandler,例如與Symfony的容器:https://symfony.com/doc/current/service_container/factories.html – dbrumann