Skip to content

Instantly share code, notes, and snippets.

@cystbear
Last active December 10, 2015 23:08
Show Gist options
  • Save cystbear/4506917 to your computer and use it in GitHub Desktop.
Save cystbear/4506917 to your computer and use it in GitHub Desktop.
<?php
namespace Acme\Calculator;
class Calculator
{
public $a;
public $b;
public function __construct($a, $b)
{
$this->a = $a;
$this->b = $b;
}
public function add($a, $b)
{
return $a + $b;
}
// ====================================================================================================================
public function getA()
{
return $this->a;
}
public function getB()
{
return $this->b;
}
public function uglyAdd()
{
return $this->getA() + $this->getB();
}
// ====================================================================================================================
protected function hiddenAdd($a, $b)
{
return $a + $b;
}
}
<?php
namespace Acme\Tests;
class CalculatorTest extends \PHPUnit_Framework_TestCase
{
public function calcData()
{
return array(
array(array(1, 3), 4),
array(array(5, 5), 10),
array(array(3, 9), 12),
array(array(4, 3), 7),
array(array(0, -1), -1),
);
}
public function mockObjectWipeAllMethodsAndAlwaysWillReturnNullWithout_SET_METHODS_Call()
{
$caclMock = $this->getMockBuilder('Acme\Calculator\Calculator')
->disableOriginalConstructor()
// uncomment and tune me, pleeease
// ->setMethods(null)
->getMock()
;
$this->assertEquals(null, $caclMock->add(1, 2));
}
/**
* @dataProvider calcData
*/
public function testCalcAddMethod($data, $result)
{
$caclMock = $this->getMockBuilder('Acme\Calculator\Calculator')
->disableOriginalConstructor()
->setMethods(null)
->getMock()
;
$this->assertEquals($result, $caclMock->add($data[0], $data[1]));
}
/**
* @dataProvider calcData
*/
public function testCalcUglyAddMethod($data, $result)
{
$caclMock = $this->getMockBuilder('Acme\Calculator\Calculator')
->disableOriginalConstructor()
->setMethods(array('getA', 'getB'))
->getMock()
;
$caclMock->expects($this->any())->method('getA')->will($this->returnValue($data[0]));
$caclMock->expects($this->any())->method('getB')->will($this->returnValue($data[1]));
$this->assertEquals($result, $caclMock->uglyAdd());
}
/**
* @dataProvider calcData
*/
public function testCalcHiddenAddMethod($data, $result)
{
$caclMock = $this->getMockBuilder('Acme\Calculator\Calculator')
->disableOriginalConstructor()
->setMethods(null)
->getMock()
;
$reflMethod = new \ReflectionMethod($caclMock, 'hiddenAdd');
$reflMethod->setAccessible(true);
$this->assertEquals($result, $reflMethod->invokeArgs($caclMock, array($data[0], $data[1])));
}
}
@spolischook
Copy link

We don't need use setMethods() at testCalcHiddenAddMethod because we use a Reflection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment