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?
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 .
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 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.
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.
Yes, it's quite simple, try this:
$classA->expects($this->never())->method($this->anything());
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:
->expects(self::never())->method(self::anything())
to all of them->expects(self::never())->method(self::anything())
you can'tWorks for PhpUnit v7.5.4 (and probably, later ones).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With