单元测试

  • PHPUNIT本身是不支持异步框架的测试的,我们在使用PHPUNIT时,做了一些改变。
  • PHPUNIT中的注解无法生效
  • 所有测试方法以unitDemo(),以unit开头。区别于test开头

测试建议,我们建议对聚合层与服务层统一做单元测试的编写。(数据库环境的配置,建议在config下面新增test配置文件,来跑单元测试)

聚合层测试示例

  1. <?php
  2. namespace src\Shop\Tests\Api;
  3. use Test;
  4. use AsyncHttp;
  5. class AuthTest extends Test
  6. {
  7. public function unitLoginAction()
  8. {
  9. $http = new AsyncHttp('http://127.0.0.1:9777');
  10. $res = (yield $http->post('/api/shop/login', ['account' => '00000001', 'password' => '2skn2w']));
  11. $data = json_decode($res->body, true);
  12. $this->assertEquals(1011, $data['code']);
  13. $res = (yield $http->post('/api/shop/login', ['account' => '00000001', 'password' => '1']));
  14. $data = json_decode($res->body, true);
  15. $this->assertEquals(1003, $data['code']);
  16. $res = (yield $http->post('/api/shop/login', ['account' => '18768176260', 'password' => '11111']));
  17. $data = json_decode($res->body, true);
  18. $this->assertEquals(200, $data['code']);
  19. }
  20. }

service测试服务的配置

  1. //用于测试
  2. 'test' => [
  3. //本机当前内网ip
  4. 'ip' => '127.0.0.1',
  5. 'serv' => '0.0.0.0',
  6. 'port' => 9511,
  7. 'config' => [
  8. 'daemonize' => true,
  9. 'worker_num' => 2,
  10. 'max_request' => 50000,
  11. 'task_worker_num' => 5,
  12. 'task_max_request' => 50000,
  13. 'heartbeat_idle_time' => 300,
  14. 'heartbeat_check_interval' => 60,
  15. 'dispatch_mode' => 3,
  16. 'log_file' => 'runtime/service/test/test.log',
  17. ]
  18. ],

test环境不设置public的属性,将公开所有服务供调用

服务层测试

  1. <?php
  2. namespace src\Service\Sms\Tests;
  3. use Test;
  4. class SmsServiceTest extends Test
  5. {
  6. public function unitSendSms()
  7. {
  8. $res = (yield service('test')->call("Sms\Sms::sendSms", ['mobile' => '18768176260']));
  9. $this->assertEquals(['code' => 200], $res);
  10. }
  11. public function unitIsActiveCode()
  12. {
  13. $res = (yield service('test')->call("Sms\Sms::isActiveCode", ['mobile' => '18768176260', 'code' => 1234]));
  14. $this->assertTrue($res);
  15. }
  16. }

单独测试服务层流程

  • 启动test服务 app/service test
  • 开始测试 phpunit —bootstrap app/test.php src/Service

测试聚合层与服务层流程

  • 启动test服务 app/service test
  • 启动主服务 php server.php
  • 开始测试 phpunit —bootstrap app/test.php src