PhpUnit 接口API单元测试

好久不见. 提交于 2020-01-18 06:27:30

一,安装PhpUnit

1.下载phpunit:点击进入

2.配置phpunit:

1)添加环境变量

右键 我的电脑 ,选择 属性 。点击左侧的 高级系统设置 。此时弹出 系统属性 ,选择 高级 选项卡,点击右下角的 环境变量 。 在用户变量里面,双击 PATH ,在 变量值 后面添加 ;D:\repository\CourseManagement\mobile_api_test (注意最前面的分号,路径填存放phpunit.phar的路径)。配置这个是为了在任意位置都能使用PHPUnit,不配置的话,需要在phpunit.phar的路径下才能使用PHPUnit。

2)配置:

进入存放phpunit.phar的路径,命令窗口运行

echo @php "%~dp0phpunit.phar" %* > phpunit.cmd

二,项目目录文件

1.API请求类

目录:./lib/CurlClient.php

<?php
/**
 * 封装curl的http客户端操作类
 */
class CurlClient {
    /**
     * 执行get请求
     *
     * @access public
     * @param string $url 远程地址
     * @param string $cookie cookie
     * @param array $options curl配置
     * @param integer $time_out 读取数据超时时间
     * @param integer $con_timeout 连接超时时间
     * @return array
     */
    public function get($url,$cookie="", array $options=array(), $time_out=30, $con_timeout=20) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $con_timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $time_out);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);

        foreach ($options as $key => $val) {
            curl_setopt($ch, $key, $val);
        }
        unset($val);

        // 执行远程请求,并清除utf8的bom输出
        $content = $this -> remove_utf8_bom(curl_exec($ch));
        // 执行之后才能获取状态码
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if($httpcode != 200){
            die("网络错误");
        }

        return $content;
    }

    /**
     * 执行post请求
     *
     * @access public
     * @param string $url 远程地址
     * @param mixed $data 数据集合
     * @param string $cookie cookie
     * @param array $options curl配置
     * @param integer $timeout 读取数据超时时间
     * @param integer $con_timeout 连接超时时间
     * @return string
     */
    public function post($url, $data=null,$cookie="",$is_show_header=0, array $options=array(), $timeout=30, $con_timeout=20) {

        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HEADER, $is_show_header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $con_timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);

        !empty($data) and curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        foreach ($options as $key => $val) {
            curl_setopt($ch, $key, $val);
        }
        unset($val);

        // 执行远程请求,并清除utf8的bom输出
        $ch_res = curl_exec($ch);
        if($is_show_header){
            $content  = $this -> get_cookie($ch_res);
        }else{
            $content  = $this -> remove_utf8_bom($ch_res);
        }
        //执行之后才能获取状态码
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($httpcode != 200){
            die("网络错误");
        }
        curl_close($ch);

        return $content;
    }

    /**
     * 清除utf-8的bom头
     *
     * @access public
     * @param string $text 字符串
     * @return string
     */
    private function remove_utf8_bom($text) {
        $bom = pack('H*', 'EFBBBF');
        $text = preg_replace("/^{$bom}+?/", '', $text);

        return $text;
    }
    private function get_cookie($text){
        list($header, $body) = explode("\r\n\r\n", $text);
        preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
        $cookie = explode(';', $matches[1])[0];
        return $cookie;
    }
}

/* End of this file */

2.基础配置类:配置域名,引用请求类

目录:./project/config.php

<?php
require_once(dirname(__FILE__)."/../lib/CurlClient.php");
define("PREFIX", "http://localhost.insure.qy.com");

3.API单元测试类:

目录:./project/TestAPI.php

<?php
require_once(dirname(__FILE__) . '/config.php');
use PHPUnit\Framework\TestCase;

class TestAPI extends TestCase
{
    /** 测试登录,并保持cookie */
    public function testLogin()
    {
        $param = array(
            "ajax_act"=>"login",
            'data' => '{"acct":"admin","password":"adminpass","code":"","cache_acct":1}'
        );
        $url = '/index.php?m=login';
        $cookie = $this->get_post_cookie($url, $param);
        file_put_contents("./cookie.txt",$cookie);
        $this->assertEquals(1, 1);

    }
    /** 100 保存表单 */
    public function testForm100()
    {
        $param = array(
            'data' => '{"title_item":"input157846865167924"}'
        );
        $url = '/index.php?model=form&m=ajax&cmd=100';
        $this->call_post($url, $param);
    }
    /** 101 获取表单列表 */
    public function testForm101()
    {
        $param = array();
        $url = '/index.php?model=form&m=ajax&cmd=101';
        $this->call_post($url, $param);
    }

    private function call_get($path, $param, $expect = '0')
    {
        $curl = new CurlClient();
        $url = PREFIX . "$path?" . http_build_query($param);
        $buf = $curl->get($url);
        $obj = json_decode($buf, True);
        $this->assertEquals($obj['errcode'], $expect);
        return $obj;
    }

    private function call_post($path, $param, $expect = '0')
    {
        $curl = new CurlClient();
        $url = PREFIX . $path ;
        $cookie = file_get_contents("./cookie.txt");
        $buf = $curl->post($url,$param,$cookie);
        $obj = json_decode($buf, True);
        if($obj['errcode'] != 0) {
            print_r([
                "url"=>$url,
                "obj"=>$obj
            ]);
            die;
        }
        $this->assertEquals($obj['errcode'], $expect);
        return [$obj,$cookie];
    }
    private function get_post_cookie($path, $param)
    {
        $curl = new CurlClient();
        $url = PREFIX . $path ;
        $cookie = $curl->post($url,$param,"",1);
        return $cookie;
    }
}

三,测试运行

phpunit TestFormApi.php

四,正常结果

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!