【问题标题】:PHPUnit + Guzzle : Cookie persistence between test methodsPHPUnit + Guzzle:测试方法之间的 Cookie 持久性
【发布时间】:2018-12-19 08:22:34
【问题描述】:

我正在使用 PHPUnit 和 Guzzle 进行 API 单元测试。我遇到的问题是我无法或我无法真正弄清楚如何在我的测试方法之间保留 cookie。或者也许我做错了^^

第一个测试testGetFirst 获取数据并在服务器端设置会话cookie。响应有一个带有正确 cookie 的 Set-Cookie 标头。

如果 cookie 存在,第二个测试 testGetSecond 应该返回一个数据集。不幸的是,Guzzle::Client 似乎没有在方法之间存储/持久化 cookie。

    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    class MyTest extends Testcase
    {
        public $guzzleClient;

        /**
         * @before
         */
        function initVariables() {
            $this->guzzleClient = new Client([
                'base_uri' => 'http://apiuri.com',
                'cookies'  => true
            ]);
        }


        // This call get some data and set a cookie (session cookie) on server side          
        function testGetFirst() {
            $params = [
                'query' => [
                    'param1' => 'myparam'
                ]                
            ];

            $response = $this->guzzleClient->request('GET', '/', $params);
            // if I print out the response headers I get my cookie in 'Set-Cookie' header
            // I suppose the cookie has been set correctly 
            print_r($response->getHeaders());

            // if I print out the client conf cookie, I get the cookie too
            print_r($this->guzzleClient->getConfig('cookies')->toArray());
        }

        // This call get data to have access it need to use a cookie that has been set by testGetFirst
        // But unfortunatelly the cookie is empty while making the request
        /**
         * @depends testGetFirst
         */
        function testGetSecond() {
            $params = [
                'query' => [
                    'param1' => 'hello'
                ]
            ];

            // if I print out the client conf cookie, cookies is empty
            print_r($this->guzzleClient->getConfig('cookies')->toArray());

            $response = $this->guzzleClient->request('GET', '/second', $params);             
            // as  the request can't access to a cookie it sends an error response
        }


    }

我知道我可以在每种方法中使用 CookieJar 并将 Set-Cookie 值传递给 Jar 但我想避免它。

您有什么想法或建议吗?

非常感谢您的帮助。

【问题讨论】:

    标签: php cookies phpunit session-cookies guzzle


    【解决方案1】:

    由于initVariables方法的@before注解,这个方法在每次测试之前执行。该方法是在每次测试之前创建一个新客户端。

    为了解决您的特殊情况,由于您使用的是@depends testGetFirst 注释,您可以让testGetFirst 方法返回客户端对象。然后testGetSecond 方法可以将其作为参数接收。检查Test Dependencies documentation 以获取有关将参数传递到依赖测试的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      • 2020-04-16
      • 2012-05-08
      • 2012-10-22
      • 2021-03-20
      • 2013-03-13
      • 1970-01-01
      相关资源
      最近更新 更多