April 27, 201214 yr I am experimenting with NetBeans and PHPUnit but I can't find examples with PHP class methods that work with objects. For example I have two PHP classes: <?php class A { public function __construct($value) { if(is_int($value)) { $this->value = $value; } else { throw new InvalidArgumentException('Value not an int.'); } } public $value; } class B { public function __construct(A $object1, A $object2) { { $this->object1 = $object1; $this->object2 = $object2; } } public function getNewObject() { return new A($this->object1->value + $this->object2->value); } private $object1; private $object2; } ?> I want to test if B::getNewObject() returns an instance of A and if that instance is the same as a previously created A instance. I added some code to the created test class stub. This is what I have so far: <?php require_once dirname(__FILE__) . '/../../Classes/TestClass.php'; /** * Test class for B. * Generated by PHPUnit on 2012-04-27 at 18:21:57. */ class BTest extends PHPUnit_Framework_TestCase { /** * @var B */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $A1 = new A(1); $A2 = new A(2); $this->object = new B($A1, $A2); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } /** * @covers B::getNewObject * @todo Implement testGetNewObject(). */ public function testGetNewObject() { $expected = new A(3); $actual = $this->object->getNewObject(); $this->assertInstanceOf(get_class($expected), $actual); $this->assertEquals($expected, $actual); } } ?> Both asserts pass, but I am not sure if I got things right. Any available examples online that I can study?
April 28, 201214 yr Looks fine to me. Most PHP frameworks come with test cases, so maybe you can browse some of their tests if its example code you're looking for. http://framework.zend.com/svn/framework/standard/trunk/tests/Zend/
April 28, 201214 yr assertInstanceOf looks right to me. Try TDD - at least that way you get to fail all your tests first.
Create an account or sign in to comment