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

Laravel unit testing same function twice and different output

我对 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 函数获得两个不同的输出。

使用 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

callGet().

设置一系列 return 值或闭包

andReturn(value1, value2, ...)

Sets up a sequence of return values or closures. For example, the first call will return value1 and the second value2. Note that all subsequent calls to a mocked method will always return the final value (or the only value) given to this declaration.

docs.mockery

下面展示了如何在 PHPUnit mocks 和 mockery 中做到这一点。

<?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());
    }
}