Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking methods to throw Error phpunit

Tags:

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?

like image 595
Nikhil Kuriakose Avatar asked Aug 27 '17 12:08

Nikhil Kuriakose


People also ask

How to mock method in PHPUnit?

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.

What is stub in PHPUnit?

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 test mocking?

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.


1 Answers

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

like image 174
Nikhil Kuriakose Avatar answered Oct 02 '22 15:10

Nikhil Kuriakose