Laravel单元测试两次相同的功能和不同的输出

时间:2016-10-11 08:58:31

标签: unit-testing phpunit laravel-5.2 integration-testing

我对Laravel单元测试有点新意。我需要通过为单元测试调用相同的repo函数来获得不同的输出。

到目前为止,我的测试是这样的:

public function testReportOffdayWorked()
{
    $input = [
        'from_date' => '2016/01/01',
        'to_date' => '2016/01/03',
    ];

    $webServiceRepositoryMock = Mockery::mock('App\Repositories\WebServiceRepository');
    $webServiceRepositoryMock->shouldReceive('callGet')->twice()->andReturn($this->issues);
    $this->app->instance('App\Repositories\WebServiceRepository', $webServiceRepositoryMock);

    $this->call('post', '/reporting/portal/report-offdays', $input);
    $this->assertResponseOk();
    $this->assertTrue($this->response->original->getName() == "Reporting::report_offday_worked");
}

我想为callGet函数获得两个不同的输出。

2 个答案:

答案 0 :(得分:0)

如何使用PHPUnit模拟框架?

$mock = $this->getMock('ClassName');  

$mock->expects($this->at(0))
     ->method('getInt')
     ->will($this->returnValue('one'));

$mock->expects($this->at(1))
     ->method('getInt')
     ->will($this->returnValue('two'));

echo $mock->getInt(); //will return one
echo $mock->getInt(); //will return two

答案 1 :(得分:0)

callGet()设置一系列返回值或闭包。

  

andReturn(value1, value2, ...)

     

设置一系列返回值或闭包。例如,第一个调用将返回value1和第二个值2。请注意,对模拟方法的所有后续调用将始终返回给予此声明的最终值(或唯一值)。

     

- docs.mockery

以下显示了如何在PHPUnit模拟和嘲弄中执行此操作。

<?php

class The {
    public function answer() { }
}

class MockingTest extends \PHPUnit_Framework_TestCase
{
    public function testMockConsecutiveCalls()
    {
        $mock = $this->getMock('The');
        $mock->expects($this->exactly(2))
             ->method('answer')
             ->will($this->onConsecutiveCalls(4, 2));

        $this->assertSame(4, $mock->answer());
        $this->assertSame(2, $mock->answer());
    }

    public function testMockeryConsecutiveCalls()
    {
        $mock = Mockery::mock('The');
        $mock->shouldReceive('answer')->andReturn(4, 2);

        $this->assertSame(4, $mock->answer());
        $this->assertSame(2, $mock->answer());
    }
}