2

I'm writing an integration test on a plugin that changes the action of an existing form.

The plugin calls a helper method that decides whether the url should be changed and returns the result.

I learned from Vinai Kopps very nice tutorials on testing that I could add a mocked sharedinstance to the objectmanager. This mock would then be used when the class is created. I think the following test uses this principe and it runs correctly:

    public function testUrlIsChangedByPlugin()
{
    $mockHelper = $this->getMockBuilder(Helper::class)
        ->setMethods(['getBooleanFromHelper'])
        ->disableOriginalConstructor()
        ->getMock();
    $mockHelper->expects($this->once())->method('getBooleanFromHelper')->willReturn(true);


    $this->objectManager->configure([Helper::class => ['shared' => true]]);
    $this->objectManager->addSharedInstance($mockHelper, Helper::class);

    /** @var FormBlock $formBlock */
    $formBlock = $this->objectManager->create(FormBlock::class);
    $this->assertContains('new/action/path', $formBlock->getFormAction());
}

Directly after this test, I would like to test nearly the same, but now the mocked helper should return false. It looks like this:

    public function testUrlIsNotChangedByPlugin()
{
    $mockHelper = $this->getMockBuilder(Helper::class)
        ->setMethods(['getBooleanFromHelper'])
        ->disableOriginalConstructor()
        ->getMock();
    $mockHelper->expects($this->once())->method('getBooleanFromHelper')->willReturn(false);

    $this->objectManager->configure([Helper::class => ['shared' => true]]);
    $this->objectManager->addSharedInstance($mockHelper, Helper::class);

    /** @var FormBlock $formBlock */
    $formBlock = $this->objectManager->create(FormBlock::class);
    $this->assertContains('old/action/path', $formBlock->getFormAction());
}

This second test fails (Method was expected to be called 1 times, actually called 0 times)

When I look in the debugger, the first time the mocked shared instance looks like this: the mock is complete with a stubbed value for the helper function

The second time it looks like this:

The mock is not complete, invocationMocker is null

I tried removing the shared instance in tearDown() ($this->objectManager->removeSharedInstance(Helper::class);), but that didn't help.

My questions:

  1. What could be the reason that the mocked shared instance misses the expected return method the second time the nearly identical test is run?
  2. Is this approach any good, or should I have constructed the plugin (or test) in a completely different way? (I am actually most interested in this)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.