0

I'm writing tests against the following class:

abstract class EmailMessageRecipient
{
    private $_address = null;

    public function setAddress($address)
    {
        $this->_address = $address;
        return $this;
    }

    public function getAddress()
    {
        return $this->_address;
    }

}

The test looks like this:

class EmailMessageRecipientTest extends PHPUnit_Framework_TestCase
{
    private $_test_object;

    protected function makeTestObject()
    {
        return $this->createMock(EmailMessageRecipient::class);
    }

    public function setUp()
    {
        $this->_test_object = $this->makeTestObject();
    }

    public function testAddress()
    {
        $this->_test_object->setAddress('blah@example.com');
        $this->assertEquals('blah@example.com', $this->_test_object->getAddress());
    }
}

PHPUnit fails the test with the message Failed asserting that null matches expected 'blah@example.com'.. So $this->_test_object->getAddress() is returning null instead of the email address that was passed to it. Why is this happening and how do I adjust the test so that it passes.

Mocking the setAddress() and getAddress() methods is not an acceptable answer. The purpose of this test is to cover setAddress() and getAddress().

Jay Bienvenu
  • 3,069
  • 5
  • 33
  • 44

1 Answers1

1

If you test an abstract class you should use: getMockForAbstractClass:

The getMockForAbstractClass() method returns a mock object for an abstract class. All abstract methods of the given abstract class are mocked. This allows for testing the concrete methods of an abstract class.

Example 9.19: Testing the concrete methods of an abstract class

<?php
use PHPUnit\Framework\TestCase;

abstract class AbstractClass
{
    public function concreteMethod()
    {
        return $this->abstractMethod();
    }

    public abstract function abstractMethod();
}

class AbstractClassTest extends TestCase
{
    public function testConcreteMethod()
    {
        $stub = $this->getMockForAbstractClass(AbstractClass::class);

        $stub->expects($this->any())
             ->method('abstractMethod')
             ->will($this->returnValue(true));

        $this->assertTrue($stub->concreteMethod());
    }
}
?>
k0pernikus
  • 60,309
  • 67
  • 216
  • 347