If I have a class A that interacts with class B then in my tests I want to mock class B so that I can test class A in isolation.
This is easy to do in PHPUnit with "getMock('classname')".
My problem currently is: If class A uses multiple instances of class B I can’t simulate this with "getMock('B')" because it appears that "getMock" will not return multiple instances if called multiple times but always the same mock of class B.
Following Example:
<?php
class A()
{
private class_b_1;
private class_b_2;
public function setClassB1(B $class_b)
{
$this->class_b_1 = $class_b;
}
public function setClassB2(B $class_b)
{
$this->class_b_2 = $class_b;
}
}
And in my tests:
$mock_one_of_class_b = $this -> getMock('B');
$mock_two_of_class_b = $this -> getMock('B');
Then $mock_one_of_class_b is the same object as $mock_two_of_class_b.
How can I mock multiple instances of a class with PHPUnit?
Thanks in advance!
Actually the
getMockmethod creates different instances of mocked class. Take a look on this example:Now we create test for it:
Pay attention on the second argument in
getMockmethod. In that argument you tellphpunitwhich methods will be mocked. If you don’t pass any argument at all – thenphpunitassume you want mock all methods from the object. So, if you passarray('someNonExistingMethod')then there won’t be any mocked method (and “real” methods will be called on invocations).