01/11/2017 - PHPUNIT
This example shows us how to test traits.
namespace Inanzzz\ApplicationBundle\Util;
trait CalculatorUtil
{
public function sum($a, $b)
{
return $a+$b;
}
public function sub($a, $b)
{
if ($a == 0) {
return;
}
return $a-$b;
}
}
namespace tests\Inanzzz\ApplicationBundle\Util;
use Inanzzz\ApplicationBundle\Util\CalculatorUtil;
use PHPUnit\Framework\TestCase;
use PHPUnit_Framework_MockObject_MockObject;
class CalculatorUtilTest extends TestCase
{
/** @var CalculatorUtil|PHPUnit_Framework_MockObject_MockObject */
private $calculatorTraitMock;
protected function setUp()
{
$this->calculatorTraitMock = $this->getMockForTrait(CalculatorUtil::class);
}
protected function tearDown()
{
$this->calculatorTraitMock = null;
}
public function testSum()
{
$this->assertEquals(3, $this->calculatorTraitMock->sum(1, 2));
}
public function testSub()
{
$this->assertEquals(3, $this->calculatorTraitMock->sub(5, 2));
$this->assertEquals(-1, $this->calculatorTraitMock->sub(1, 2));
$this->assertEquals(-3, $this->calculatorTraitMock->sub(-1, 2));
$this->assertEquals(-3, $this->calculatorTraitMock->sub(-2, 1));
$this->assertEquals(3, $this->calculatorTraitMock->sub(1, -2));
$this->assertEquals(3, $this->calculatorTraitMock->sub(2, -1));
$this->assertEquals(1, $this->calculatorTraitMock->sub(-1, -2));
$this->assertEquals(-1, $this->calculatorTraitMock->sub(-2, -1));
$this->assertEquals(0, $this->calculatorTraitMock->sub(-2, -2));
$this->assertEquals(1, $this->calculatorTraitMock->sub(1, 0));
$this->assertNull($this->calculatorTraitMock->sub(-0, 2));
$this->assertNull($this->calculatorTraitMock->sub(0, 2));
}
}
$ vendor/bin/phpunit
PHPUnit 4.8.36 by Sebastian Bergmann and contributors.
..
Time: 199 ms, Memory: 4.00MB
OK (2 tests, 13 assertions)