Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit assert no method is called

I have a ClassA that uses a ServiceB. In a certain case, ClassA should end up not invoking any methods of ServiceB. I now want to test this and verity no methods are indeed called.

This can be done as follows:

$classA->expects( $this->never() )->method( 'first_method' ); $classA->expects( $this->never() )->method( 'second_method' ); ... 

Is there a way to simply state "no method should be called on this object" rather then having to specify a restriction for each method?

like image 496
Jeroen De Dauw Avatar asked Sep 11 '13 15:09

Jeroen De Dauw


People also ask

What is assertion in PHPUnit?

The assertion methods are declared static and can be invoked from any context using PHPUnit\Framework\Assert::assertTrue() , for instance, or using $this->assertTrue() or self::assertTrue() , for instance, in a class that extends PHPUnit\Framework\TestCase .

What is a PHPUnit test?

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.

How do I run a PHPUnit test?

How to Run Tests in PHPUnit. You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status.

Is PHPUnit a framework?

PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks. The currently supported versions are PHPUnit 9 and PHPUnit 8.


2 Answers

Yes, it's quite simple, try this:

$classA->expects($this->never())->method($this->anything()); 
like image 140
Cyprian Avatar answered Oct 11 '22 10:10

Cyprian


You can use method MockBuilder::disableAutoReturnValueGeneration.

For example, in your test overwrite default TestCase::getMockBuilder:

    /**      * @param string $className      * @return MockBuilder      */     public function getMockBuilder($className): MockBuilder     {         // this is to make sure, that not-mocked method will not be called         return parent::getMockBuilder($className)             ->disableAutoReturnValueGeneration();     } 

Advantages:

  • all your mocks won't be expected to call anything than mocked methods. No need to bind ->expects(self::never())->method(self::anything()) to all of them
  • you still can set new mocks. After ->expects(self::never())->method(self::anything()) you can't

Works for PhpUnit v7.5.4 (and probably, later ones).

like image 43
Oleksandr Boiko Avatar answered Oct 11 '22 10:10

Oleksandr Boiko