Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

This example shows us how to test traits.


CalculatorUtil


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;
}
}

CalculatorUtilTest


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));
}
}

Test


$ vendor/bin/phpunit
PHPUnit 4.8.36 by Sebastian Bergmann and contributors.

..

Time: 199 ms, Memory: 4.00MB

OK (2 tests, 13 assertions)