在phpunit中mock支付宝回调测试用例样式代码分享
php  /  管理员 发布于 2年前   459
分享两种测试用例方式代码: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);
}
注意
支付宝的回调数据,只要是不去用真实环境,就得伪造,否则就需要指定请求数据并绑定对应的返回数据,去判断;
还有就是自己封装请求的话就需要自己去实现对应的数据验证;
如果用三方的包,一般都有测试文件,参考他们的单元测试去实现就行;
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号