How to add Mockery assertion counts to PHPUnit

Have you ever seen this error message when running PHPUnit with Mockery assertions?

This test did not perform any assertions

It's rather confusing. It needn't be though. PHPUnit (specifically this version, 7.0.2) defaults it's Mark Test As Risky flag to true if it does not contain any assertions in it.

Mockery assertions are by default not part of PHPUnit assertion counts so a pure Mockery unit test will not result in any assertions fired according to PHPUnit. Below is the code that will run to mark a unit test as risky.

<?php
// vendor/phpunit/phpunit/src/Framework/TestResult.php
// Defaults to true

/**
 * @var bool
 */
protected $beStrictAboutTestsThatDoNotTestAnything = true;

...

// vendor/phpunit/phpunit/src/Framework/TestResult.php#785
...
    if ($this->beStrictAboutTestsThatDoNotTestAnything &&
        $test->getNumAssertions() == 0) {
        $risky = true;
    }

This is obviously not what we want when running our test suites because some unit tests will only be Mockery assertions that are asserting that dependencies were called.

To fix that add the following code in your base tearDown() method:

 /**
     * Base tear down
     */
    function tearDown()
    {
        parent::tearDown();
        
        if ($container = \Mockery::getContainer()) {
            $this->addToAssertionCount($container->mockery_getExpectationCount());
        }
        
        Mockery::close();
    }

That's it. No more false risky tests and Mockery assertions are added to the list of things tested. Neat!

tests-output-example

Show Comments

Get the latest posts delivered right to your inbox.