1
時,嘲笑security.context被視爲非對象。我試圖測試我的服務。此服務調用security.context
等其他服務。當撥打AlbumHandler
時,模擬在security.context
步驟失敗。當調用
錯誤:
PHP Fatal error: Call to a member function getToken() on a non-object
代碼:
public function setUp()
{
$this->container = $this->getMock('\Symfony\Component\DependencyInjection\ContainerInterface');
}
public function testAdd()
{
// The user I want to return
$user = $this->getMock('\MyProject\Bundle\UserBundle\Entity\User');
// I create a Token for mock getUser()
$token = $this->getMock('\Symfony\Component\Security\Core\Authentication\Token');
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user));
// I mock the service. PHPUnit don't return an error here.
$service = $this->getMockBuilder('Symfony\Component\Security\Core\SecurityContextInterface')
->disableOriginalConstructor()
->getMock();
$service->expects($this->once())
->method('getToken')
->will($this->returnValue($token));
// I replace the real service by the mock
$this->container->set('security.context', $service);
// It fails at the constructor of this service.
$albumHandler = new AlbumHandler($entityManager, $this->container, 'MyProject\Bundle\AlbumBundle\Entity\Album');
$this->assertEquals($albumHandler, $albumHandler);
}
下面的代碼是AlbumHandler
的constuctorpublic function __construct(ObjectManager $om, Container $container, $entityClass)
{
$this->om = $om;
$this->entityClass = $entityClass;
$this->repository = $this->om->getRepository($this->entityClass);
$this->container = $container;
// fail here
$this->user = $this->container->get('security.context')->getToken()->getUser();
}
感謝@Matteo!但現在,我在下一步中遇到錯誤:'.PHP致命錯誤:調用未定義的方法Mock_Token_66794207 :: getUser()'。你在我的代碼中看到錯誤嗎? – Gura 2014-10-09 08:56:36
http://stackoverflow.com/questions/12599957/undefined-method-on-mock-object-implementing-a-given-interface-in-phpunit幫助我呢! – Gura 2014-10-09 09:11:24
我複製你的問題並修復它!我編輯我的回覆。 – Matteo 2014-10-09 09:21:58