Quantcast
Channel: Franz's Web Blog
Viewing all articles
Browse latest Browse all 26

My take on Mocks VS Stubs

$
0
0
I sometimes get confused on the difference between a mock and a stub. Actually I still get confused from time to time but I'll spit out my thoughts right now.

Example:
class Math
{
public function add($arg1, $arg2)
{
if (!is_numeric($arg1) || !is_numeric($arg2)) {
throw new Exception('cannot add non numerics');
}
return $arg1 + $arg2;
}
}

class Person
{
public function getTotalItems(Math $math, $shoes, $shirts)
{
return $math->add($shoes, $shirts);
}
}

Mock Unit Test:
public function getTotalItemsTest()
{
$mockMath = $this->getMockBuilder('Math')
->setMethods(array('add'))
->getMock();
$mockMath->expects($this->once())
->method('add')
->with($this->isType('numeric'), $this->isType('numeric'))
->will($this->returnCallback(function ($arg1, $arg2) {
return $arg1 + $arg2;
}));

$total = $person->getTotalItems($mockMath, 2, 3);
$this->assertEquals(5, $total);
}

Stub Unit Test:
public function getTotalItemsTest()
{
$stubMath = $this->getMockBuilder('Math')
->setMethods(array('add'))
->getMock();
$stubMath->expects($this->any())
->method('add')
->will($this->returnValue(5));

$total = $person->getTotalItems($stubMath, 2, 3);
$this->assertEquals(5, $total);
}

This is not the best example but you get the groove? When you mock an object, you set an "expectation" for the object method you are mocking. In the case above, we are checking that add() only accepts numerical inputs. Usually, a dead give away is we are using with() to set our expectation. In contrast to a stub, we are just returning straight the result.

Note that the callback for a mock does not matter. I just use it for verbosity.

Viewing all articles
Browse latest Browse all 26

Trending Articles