vendredi 29 juillet 2016

Testing against early returns (defensive programming)

I am learning testing and trying to test a function using 'early returns'. The function on success sets a property in another class and on failure simply returns so in both cases it 'returns' void.

class Test
{
    private $fileHandler;
    private $config;

    public __constructor($fileHandler, $config)
    {
        $this->fileHandler = $fileHandler;
        $this->config = $config;
    }

    public function example($filePath)
    {
        $exists = $this->fileHandler->exists($filePath);

        if ($exists === false) {
             return;
        }

        $this->config->set($filePath);
    }
}

In this example I believe I can test this with two unit tests and by mocking the fileHandler class.

For a failure (early return) the $config class's method set() should not be called whilst for a success the method should be called.

However, this test passes if I try and change never() to once() making me think the entire test is bogus.

/** test */
public function config_is_not_set_with_missing_file()
{
    $fileHandlerMock = $this->getMockBuilder(fileHandler::class)->getMock;
    $fileHandlerMock->method('exists')
        ->willReturn('false');
    $configMock = $this->getMockBuilder(config::class)->getMock;

    $test = new Test($fileHandlerMock);
    $test->example('fake file path');

    $configMock->expects($this->never())
        ->method('set');
}

Aucun commentaire:

Enregistrer un commentaire