Dimitrios Desyllas
Dimitrios Desyllas

Reputation: 10166

Mocking Twig_Environment

I want to mock a Twig_Environment for phpUnit So on my test I called:

   $twigMock=$this->getMockBuilder(\Twig_Environment::class)
                            ->disableOriginalConstructor()
                            ->getMock()
                            ->method('render')
                            ->willReturn('');

Then I have a class:

class SampleClass
{
    private $twig=null;

    public function __construct(\Twig_Environment $twig)
    {
      $this->twig=$twig;
    }

    public function foo($param)
    {
       if(param)
       {
          $content=$this->twig->render('some_template./html.twig');
       }
       // DO other stuff
    }
}

But when I try to call on my test class:

$campleClassInstance=new SampleClass($twigMock);

I get the following error:

TypeError: Argument 2 passed to \SampleClass::__construct() must be an instance of Twig_Environment, instance of PHPUnit_Framework_MockObject_Builder_InvocationMocker given,

Do you haver any idea how to solve it?

Upvotes: 1

Views: 2099

Answers (2)

pekowal
pekowal

Reputation: 41

In symfony 4.4, the Environment class can't be mocked:

Class "Twig\TemplateWrapper" is declared "final" and cannot be mocked.

Upvotes: 4

Schleis
Schleis

Reputation: 43800

You are passing setting the variable to the return value of willReturn which doesn't return the original mock object but rather an PHPUnit_Framework_MockObject_Builder_InvocationMocker object that PHPUnit uses internally. You can't chain the mock and the expectation together in order for this to work. Change your mocking to:

$twigMock=$this->getMockBuilder(\Twig_Environment::class)
                        ->disableOriginalConstructor()
                        ->getMock();

$twigMock->method('render')
         ->willReturn('');

Upvotes: 2

Related Questions