讨论数量:
可以的
// GuzzleHttp 测试用例
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
// Create a mock and queue two responses.
$mock = new MockHandler([
new Response(200, ['X-Foo' => 'Bar']),
new Response(202, ['Content-Length' => 0]),
new RequestException("Error Communicating with Server", new Request('GET', 'test'))
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
// The first request is intercepted with the first response.
echo $client->request('GET', '/')->getStatusCode();
//> 200
// The second request is intercepted with the second response.
echo $client->request('GET', '/')->getStatusCode();
//> 202
如果不是用的 GuzzleHttp,那就需要手动去创建 phpunit 的 mock 对象。然后返回数据
// 简单的测试用例
namespace Tests;
use PHPUnit\Framework\TestCase as BaseTestCase;
class MockTest extends BaseTestCase
{
public function testMock()
{
$map = [
[1,2,3],
[10,5, 15]
];
$test = $this->createMock(test::class);
$test->expects($this->any())
->method('plus')
->will($this->returnValueMap($map));
$this->assertSame(3, $test->plus(1,2));
$this->assertSame(15, $test->plus(10,5));
$this->assertSame(16, $test->plus(10,6)); // error: $map 没有设置,mock 不认识
}
}
interface test
{
public function plus(int $a, int $b);
}
可以的
如果不是用的 GuzzleHttp,那就需要手动去创建 phpunit 的 mock 对象。然后返回数据