phpunit – mockbuilder – set mock object internal property

You can make the property public by using Reflection, and then set the desired value: $a = new A; $reflection = new ReflectionClass($a); $reflection_property = $reflection->getProperty(‘p’); $reflection_property->setAccessible(true); $reflection_property->setValue($a, 2); Anyway in your example you don’t need to set p value for the Exception to be raised. You are using a mock for being able to … Read more

How to use phpunit installed from composer?

If you followed the documentation, you have set the phpunit/phpunit dependency as a ‘dev-dependency’. If you don’t have composer, you need to install it first. This is explained in the documentation: Installation *nix or Installation Windows. If you already installed composer, it is a good practise to update composer to the latest version by running … Read more

PHPUnit: expects method meaning

expects() – Sets how many times you expect a method to be called: $mock = $this->getMock(‘nameOfTheClass’, array(‘firstMethod’,’secondMethod’,’thirdMethod’)); $mock->expects($this->once()) ->method(‘firstMethod’) ->will($this->returnValue(‘value’)); $mock->expects($this->once()) ->method(‘secondMethod’) ->will($this->returnValue(‘value’)); $mock->expects($this->once()) ->method(‘thirdMethod’) ->will($this->returnValue(‘value’)); If you know, that method is called once use $this->once() in expects(), otherwise use $this->any() see: PHPUnit mock with multiple expects() calls https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.stubs Advanced PHPUnit Testing from Mike Lively

PHPUnit Mock Objects and Static Methods

Sebastian Bergmann, the author of PHPUnit, recently had a blog post about Stubbing and Mocking Static Methods. With PHPUnit 3.5 and PHP 5.3 as well as consistent use of late static binding, you can do $class::staticExpects($this->any()) ->method(‘helper’) ->will($this->returnValue(‘bar’)); Update: staticExpects is deprecated as of PHPUnit 3.8 and will be removed completely with later versions.

How to unit test PHP traits

You can test a Trait using a similar to testing an Abstract Class’ concrete methods. PHPUnit has a method getMockForTrait which will return an object that uses the trait. Then you can test the traits functions. Here is the example from the documentation: <?php trait AbstractTrait { public function concreteMethod() { return $this->abstractMethod(); } public … Read more