在phpunit中mock支付宝回调测试用例样式代码分享

2023-06-01 00:00:00 样式 回调 支付宝

分享两种测试用例方式代码:GuzzleHttp、手动去创建phpunit的mock对象返回数据

1.GuzzleHttp 测试用例

// 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


2.手动去创建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);

}


注意

支付宝的回调数据,只要是不去用真实环境,就得伪造,否则就需要指定请求数据并绑定对应的返回数据,去判断;

还有就是自己封装请求的话就需要自己去实现对应的数据验证;

如果用三方的包,一般都有测试文件,参考他们的单元测试去实现就行;

相关文章