【问题标题】:Drupal 8 PHPUnit testing Invalid CredentialsDrupal 8 PHPUnit 测试无效凭证
【发布时间】:2020-09-23 11:06:07
【问题描述】:

我有一个要测试的类,该类使用此 module PHP HTTP 客户端用于 Emarsys Web 服务,但是当我尝试对其进行测试时,我总是会从模块本身获得 $response 作为“凭据无效”。

这是我的代码的 sn-p:(鉴于我能够为测试类正确创建 setUp(),因为我能够将它用于其他测试)

Test.php

Class TestClass extends UnitTestCase {
    public function testCreateWithValidEmail() {

        $newsletter = new Newsletter();

        $form = new FormState();
        $form->setValue('email', 'abc@def.ghi');

        $response = $newsletter->register($form);

        // Assertion here
    }
}

类.php

use Snowcap\Emarsys\CurlClient;
use Snowcap\Emarsys\Client;

Class Newsletter {
    public function register(FormStateInterface $state){
          $emailData = $state->getValue('email');

          $httpClient = new CurlClient();
          $client = new Client($httpClient, $api_username, $api_secret);
          $someData = [
             "3" => $emailData, // since 3 is the index ID for email
             // ...more data here
          ];

          $response = $client->createContact($someData);
    }
}

我是否必须在这里创建一个模拟来传递一个虚拟 api 和秘密,然后强制来自 createContact 的有效响应?

【问题讨论】:

    标签: php unit-testing phpunit drupal-8


    【解决方案1】:

    你的方向是好的。但是Newsletter 类需要注入$httpClient

    所以你将能够做到:

    $client = $this->getMockBuilder(Snowcap\Emarsys\CurlClient::class)
      ->disableOriginalConstructor()
      ->getMock();
    $response = $this->getMockBuilder(ResponseInterface::class)
      ->disableOriginalConstructor()
      ->getMock();
    $response->expects($this->any())
      ->method('getStatusCode')
      ->willReturn(Response::HTTP_OK);
    $client->expects($this->any())
      ->method('createContact')
      ->with($someData)
      ->will($this->returnValue($response));
    
    $newsletter = new Newsletter($client);
    $response = $newsletter->register($form);
    // Assertion here
    

    【讨论】:

    • 我尝试了一种不同的方法,我仍然使用依赖注入来修复响应,但是当我尝试它时这也有效。谢谢!
    猜你喜欢
    • 2020-05-06
    • 2015-03-26
    • 2013-09-19
    • 1970-01-01
    • 2019-08-14
    • 2016-08-10
    • 2021-02-25
    • 1970-01-01
    • 2018-08-08
    相关资源
    最近更新 更多