PhpUnit测试存根方法多次返回

时间:2015-06-08 16:38:58

标签: php unit-testing symfony phpunit

我正在使用symfony2进行一些PHPUnit测试。我遇到了一个特定测试的问题。

我正在测试一个响应形式我的课程当然一个回答是真的一个错误。我有一个模拟我的数据库,我有一个存根,我的databaseRepository中的一个方法。

问题是,在一次测试中,我对一个有效数组的方法执行存根,第二次测试我只想查询无效的空。

我的db MOck:

    //Setting up mock of database repository class
    $this->db = $this->getMockBuilder('DatabaseRepository')
        ->disableOriginalConstructor()
        ->getMock();

    $this->db->expects($this->any())
        ->method('getRecord')
        ->will($this->returnValue(self::$registrationRecord));

    $this->db->expects($this->any())
        ->method('getRecord')
        ->willReturn(null);

所以我试图有两个不同的期望但是这个显然不起作用.....是否有可能有一个存根方法有两个不同的回报..?

test1:

    <?php


class UnsubscribeRegistrationTemplateTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var UnsubscribeRegistrationTemplate
     */
    protected $object;

    /**
     * @var ValidationClass
     */
    public $validate;

    /**
     * @var DatabaseRepository
     */
    public $db;

    //Database Record Mock
    public static $registrationRecord = array
    (
        'rowid' => '96',
        'unsubscription' => 'N',
        'updated' => 'BB'
    );

    /**
     *
     */
    protected function setUp()
    {
        //Setting up mock of validation class
        $this->validate = $this->getMockBuilder('ValidationClass')
            ->disableOriginalConstructor()
            ->getMock();

        $this->validate->expects($this->any())
            ->method('validateInput')
            ->willReturn(true);

        //Setting up mock of database repository class
        $this->db = $this->getMockBuilder('DatabaseRepository')
            ->disableOriginalConstructor()
            ->getMock();

        $this->db->expects($this->any())
            ->method('getRegistrationRecord')
            ->will($this->returnValue(self::$registrationRecord));

        $this->db->expects($this->any())
            ->method('getRegistrationRecord')
            ->will($this->returnValue(null));

        $this->db->expects($this->any())
            ->method('setPreRegistrationEnquiryUnsubscriptionEnabled')
            ->willReturn(true);

        $this->object = $this->createUnsubscribeRegistrationTemplateInstance();
    }

    /**
     * @return UnsubscribeRegistrationTemplate
     *
     */
    public function createUnsubscribeRegistrationTemplateInstance()
    {
        //initialize Unsubscribe Registration Template
        return new UnsubscribeRegistrationTemplate
        (
            $this->validate,
            $this->db
        );
    }

    /**
     * @param array $mapping
     * @return Request
     */
    public function createRequest(array $mapping)
    {
        $request = new Request();

        foreach ( $mapping as $k =>$v)
        {
            $request->query->set($k, $v);
        }

        return $request;
    }

    /**
     *
     */
    public function testUnsubscribeRegistrationTemplateValidResponse()
    {
        $request = $this->createRequest(array(
            'registration_id' => '96',
            'source_channel' => 'BB'
        ));

        $response = new Response(
            true,
            'Unsubscription successful'
        );

        $this->assertEquals($response, $this->object->create($request));
    }

    /**
     *
     */
    public function testUnsubscribeRegistrationTemplateEmptyResponse()
    {
        $request = $this->createRequest(array(
            'registration_id' => '96',
            'source_channel' => 'BB'
        ));

        $response = new Response(
            false,
            'Registration Record Not Found.'
        );

        $this->assertEquals($response, $this->object->create($request));
    }

    /**
     *
     */
    public function testIsAlreadyRegisteredValidResponse()
    {
        //Testing record is already unsubscribed
        $registrationRecord = array(
            'unsubscription_enabled' => 'Y'
        );

        $this->assertTrue($this->object->isAlreadyUnsubscribed($registrationRecord));
    }

    /**
     *
     */
    public function testIsAlreadyRegisteredInValidResponse()
    {
        //Testing record not unsubscribed
        $registrationRecord = array(
            'unsubscription_enabled' => 'N'
        );
        $this->assertFalse($this->object->isAlreadyUnsubscribed($registrationRecord));
    }

    /**
     *
     */
    protected function tearDown()
    {
        unset($this->object);
    }

}

2 个答案:

答案 0 :(得分:3)

你可以通过多种方式做到这一点 以下两种方式可能符合您的需求。

1 - 将getRecord()移动到测试

/**
* @test
*/
public function ifTrue()
{
    $this->db->expects($this->once())
    ->method('getRecord')
    ->will($this->returnValue(self::$registrationRecord));

    $request = $this->createRequest(array(
        'id' => '10',
        'code' => 'BB'
    ));

    $response = new Response(
        true,
        'successful'
    );

    $this->assertEquals($response, $this->object->create($request));
}

/**
 * @test
 */
public function ifFalse()
{
    $this->db->expects($this->once())
    ->method('getRecord')
    ->willReturn(null);

    $request = $this->createRequest(array(
        'id' => '10',
        'code' => 'BB'
    ));

    $response = new Response(
        false,
        'Record Not Found.'
    );

    $this->assertEquals($response, $this->object->create($request));
}

正如您所看到的,有很多重复,所以让我们使用dataprovider

2 - 使用@dataProvider

protected function getDataForTest()
{
    return array(
        array(self::$registrationRecord, true, 'successful'),
        array(null, false, 'Record Not Found.')
    );
}

/**
* @dataProvider getDataForTest
* @test
*/
public function ifTrue($getRecordValue, $bool, $message)
{
    $this->db->expects($this->once())
    ->method('getRecord')
    ->will($this->returnValue($getRecordValue);

    $request = $this->createRequest(array(
        'id' => '10',
        'code' => 'BB'
    ));

    $response = new Response(
        $bool,
        $message
    );

    $this->assertEquals($response, $this->object->create($request));
}

使用@dataProvider,您可以使用任意数量的值来测试所有情况。

答案 1 :(得分:2)

我认为您应该使用PHPUnit at()方法检查某个索引处的方法调用。因此,您必须使用正确的索引调用替换expects value参数。

所以你可以使用以下代码:

//Setting up mock of database repository class
$this->db = $this->getMockBuilder('DatabaseRepository')
    ->disableOriginalConstructor()
    ->getMock();

$this->db->expects($this->at(0)) // Mock the  first call
    ->method('getRecord')
    ->will($this->returnValue(self::$registrationRecord));

$this->db->expects($this->at(1)) // Mock the  second call
    ->method('getRecord')
    ->willReturn(null);

http://www.andrejfarkas.com/2012/07/phpunit-at-method-to-check-method-invocation-at-certain-index/

希望这个帮助