Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a mock outside a test case in PhpUnit?

It may seem silly, hope not, but I want to create a service that will return mock objects for people that uses my project so they can mock all the classes from my project and test their code.

My idea was to offer this kind of service so it can be called inside other project's test cases and obtain the appropriate mock for each test.

Is that possible? Or there are other ways to do that. Btw, I can't use any mocking library because of project's limitations.

like image 417
Khriz Avatar asked Feb 17 '15 16:02

Khriz


People also ask

Which method is used to create a mock with 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 the difference between mock and stub?

Mocks verify the behavior of the code you're testing, also known as the system under test. Mocks should be used when you want to test the order in which functions are called. Stubs verify the state of the system under test.


1 Answers

Yes, it is possible. Under the hood the getMock method uses the PHPUnit_Framework_MockObject_Generator class. So you can use it directly:

PHPUnit_Framework_MockObject_Generator::getMock($originalClassName, $methods)

But you will lose all the expectation shortcuts like $this->once(). You will have to instantiate the expectations on your own:

$mock->expects(\PHPUnit_Framework_TestCase::once())

Look at the PHPUnit source code to see how the mocks are build

like image 183
Maxim Krizhanovsky Avatar answered Sep 18 '22 02:09

Maxim Krizhanovsky