Drupal 8 PHPUnit测试无效凭据

Drupal 8 PHPUnit测试无效凭据,php,unit-testing,phpunit,drupal-8,Php,Unit Testing,Phpunit,Drupal 8,我想测试一个类,它使用这个PHP HTTP客户机为Emarsys webservice服务,但是当我尝试测试它时,我总是会从模块本身获得$response,因为“凭据无效” 下面是我的代码片段:(假设我能够正确地为测试类创建setUp(),因为我能够将它用于其他测试) Test.php Class TestClass扩展了UnitTestCase{ 公共函数testCreateWithValidEmail(){ $newsletter=新新闻稿(); $form=new FormState();

我想测试一个类,它使用这个PHP HTTP客户机为Emarsys webservice服务,但是当我尝试测试它时,我总是会从模块本身获得
$response
,因为“凭据无效”

下面是我的代码片段:(假设我能够正确地为测试类创建
setUp()
,因为我能够将它用于其他测试)

Test.php

Class TestClass扩展了UnitTestCase{
公共函数testCreateWithValidEmail(){
$newsletter=新新闻稿();
$form=new FormState();
$form->setValue('email','abc@def.ghi');
$response=$newsletter->register($form);
//这里的断言
}
}
Class.php

使用Snowcap\Emarsys\CurlClient;
使用Snowcap\Emarsys\Client;
班级通讯{
公共功能寄存器(FormStateInterface$state){
$emailData=$state->getValue('email');
$httpClient=new CurlClient();
$client=newclient($httpClient,$api\u username,$api\u secret);
$someData=[
“3”=>$emailData,//因为3是电子邮件的索引ID
//…这里有更多数据
];
$response=$client->createContact($someData);
}
}

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

你的方向是正确的。但是,
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

我尝试了一种不同的方法,我仍然使用依赖注入来修复响应,但在我尝试时,这也起到了作用。谢谢