【发布时间】:2018-01-25 18:03:27
【问题描述】:
我在一些类上运行 phpunit 测试,我得到了这个错误
PHP Fatal error: Call to a member function get() on null in src/MyApp/MyBundle/Classes/Action/CopyList.php on line 415
在那一行是
$em = $dic->get('doctrine.orm.entity_manager');
来自
namespace MyApp\MyBundle\Classes\Action;
use Symfony\Component\HttpFoundation\Session;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
class CopyList extends Action {
public function __clone($task) {
$dic = Environment::getInstance()->getContainer();
$em = $dic->get('doctrine.orm.entity_manager');
$list = $em->getRepository('MyAppMyBundle:CopyList')->findByName($task);
if (!$list) {
$list = new CopyList();
$em->persist($list);
$em->flush();
}
}
从该行调用的
$clone = clone $container;
在
namespace tests\src\MyApp\MyBundle\Classes;
use Symfony\Component\HttpFoundation\Request;
abstract class TaskContextContainerTestCase extends TestCase {
public function testCloning() {
$container = $this->createInstance();
$container->setImmutable(true);
$this->assertTrue($container->isImmutable());
$clone = clone $container;
$this->assertNotEquals($container, $clone);
$this->assertFalse($clone->isImmutable());
}
我试过做类似的事情
protected function getEmMock()
{
$emMock = $this->getMock('\Doctrine\ORM\EntityManager',
array('getRepository', 'getClassMetadata', 'persist', 'flush'), array(), '', false);
$emMock->expects($this->any())
->method('getRepository')
->will($this->returnValue(new FakeRepository()));
$emMock->expects($this->any())
->method('getClassMetadata')
->will($this->returnValue((object)array('name' => 'aClass')));
$emMock->expects($this->any())
->method('persist')
->will($this->returnValue(null));
$emMock->expects($this->any())
->method('flush')
->will($this->returnValue(null));
return $emMock; // it tooks 13 lines to achieve mock!
}
来自here,但我认为我做得不对。例如,我将该代码放在TaskContextContainerTestCase 的setUp() 函数中。任何指针都非常感谢。
【问题讨论】:
-
我删除了我的答案,因为它不是解决您问题的好方法。
标签: symfony doctrine-orm phpunit