mercredi 18 novembre 2015

PHPUnit - Mocking private methods called within the same class

I've ran into a small issue with PHPUnit that I can't figure out. I'm rather familiar with mocking classes, using reflection to change visibility etc, but this one has me stumped!

I want to mock a method on a class, then test another method on that class, which calls the mocked method.

Here's a simple example,

<?php

namespace StackOverflowExample;

class Example {

    private function getValue(){

        // Method to be mocked/overwridden.
        return 10;
    }

    public function runMethod(){

        // Logic to test.
        return 'The value: ' . $this->getValue();
    }
}

Example test,

<?php

require_once './vendor/autoload.php';

class ExampleTest extends PHPUnit_Framework_Testcase {

    public function testExample(){

        $exampleMock = $this->getMockBuilder('StackOverflowExample\Example')
            ->setMethods(array('getValue'))
            ->getMock();

        $exampleMock->method('getValue')
            ->willReturn(55);

        var_dump($exampleMock->runMethod()); // The value: 10
    }
}

I'm overriding the return value of the getValue() method to 55, as you can see.

However, when calling runMethod(), the reponse is The value: 10.

I'd like this to be 55. I'm aware that i've used setMethods() only on my getValue method, as that's the only method I want to mock.

I'd like the logic contained with runMethod() to run.

If I change getValue() to public The value: 55 is returned as I expected, but I don't want getValue to be public.

Is there a reason why calling a mocked method on the same class won't work for me?

I'm aware of reflection but don't see why it would be required in this example, as getValue() is still being called from within the class.

Any help would be greatly appreciated,

Thanks, Adrian

Aucun commentaire:

Enregistrer un commentaire