PHPUnit let me make a method stub to throw an Exception, using either of:
[->will($this->throwException(..)][1]
->willThrowException(..
I need to test some cases where the method stub throws PHP Errors.
Does PHPUnit support anything like this? Any workarounds here?
PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.
We then use the Fluent Interface that PHPUnit provides to specify the behavior for the stub. In essence, this means that you do not need to create several temporary objects and wire them together afterwards. Instead, you chain method calls as shown in the example. This leads to more readable and “fluent” code.
What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.
The throwException() in PHPUnit TestCase class can take any instance of Throwable as param.
This means,
->will($this->throwException(new Error())); ->will($this->throwException(new Exception()));
are both valid
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