Skip to content

Instantly share code, notes, and snippets.

@willitscale
Created June 15, 2018 15:10
Show Gist options
  • Save willitscale/49c452e5b2a33b79f73d275805252ceb to your computer and use it in GitHub Desktop.
Save willitscale/49c452e5b2a33b79f73d275805252ceb to your computer and use it in GitHub Desktop.
Writing code to be tested
<?php
namespace App\Components\Example;
class EasyToTest extends Sample
{
public function __construct(
NestedObjectA $nestedObjectA,
NestedObjectB $nestedObjectB
) {
$this->nestedObjectA = $nestedObjectA;
$this->nestedObjectB = $nestedObjectB;
}
}
<?php
namespace App\Components\Example;
class HardToTest extends Sample
{
public function __construct()
{
$this->nestedObjectA = new NestedObjectA();
$this->nestedObjectB = new NestedObjectB(
$this->nestedObjectA
);
}
}
<?php
namespace App\Components\Example;
class NestedObjectA
{
private $i = 1;
public function foo()
{
$this->i++;
}
public function bar()
{
return $this->i--;
}
}
<?php
namespace App\Components\Example;
class NestedObjectB
{
private $nestObjectA;
public function __construct(NestedObjectA $nestedObjectA)
{
$this->nestObjectA = $nestedObjectA;
}
public function foobar()
{
$this->nestObjectA->foo();
return $this->nestObjectA->bar();
}
}
<?php
namespace App\Components\Example;
class Sample
{
/**
* @var NestedObjectA
*/
protected $nestedObjectA;
/**
* @var NestedObjectB
*/
protected $nestedObjectB;
public function doSomething()
{
return $this->nestedObjectA->bar() + 2;
}
public function doSomethingElse()
{
return $this->nestedObjectB->foobar();
}
}
<?php
use App\Components\Example\EasyToTest;
use App\Components\Example\HardToTest;
use App\Components\Example\NestedObjectA;
use App\Components\Example\NestedObjectB;
use PHPUnit\Framework\TestCase;
class TestingSamples extends TestCase
{
/**
* @var NestedObjectA
*/
private $nestedObjectAMock;
/**
* @var NestedObjectB
*/
private $nestedObjectBMock;
public function setup()
{
$this->nestedObjectAMock = $this->getMockBuilder(
NestedObjectA::class
)
->disableOriginalConstructor()
->getMock();
$this->nestedObjectBMock = $this->getMockBuilder(
NestedObjectB::class
)
->disableOriginalConstructor()
->getMock();
}
/**
* @test
*/
public function testHardToTest()
{
$hardToTest = new HardToTest();
$this->assertEquals(
3,
$hardToTest->doSomething(),
"Returning value does not equal 3"
);
}
/**
* @test
*/
public function testDoSomethingInEasyToTest()
{
$easyToTest = new EasyToTest(
$this->nestedObjectAMock,
$this->nestedObjectBMock
);
$this->nestedObjectAMock
->expects(self::once())
->method('bar')
->with();
$easyToTest->doSomething();
}
public function testDoSomethingElseInEasyToTest()
{
// Write me
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment