MockObject属性在构造函数后被清除

时间:2018-12-05 13:13:26

标签: php phpunit

大家好,我目前正在为我的项目中的类中的一个函数编写测试。

function theTestFunction()
{
  $companyMock = $this->createMock(Company::class);
  $companyMock->method('getUser')->willReturn(new User());
  $companyMock->method('isActive')->willReturn(false);
  $companyMock->expects($this->once())->method('setActive')->with(true)->willReturn($companyMock);

  $manager = $this->getMockBuilder(CompanyManager::class)
    ->setMethods(['updateNewsletter'])
    ->setConstructorArgs([$companyMock])
    ->getMock();
  $manager->expects($this->once())->method('updateNewsletter');
  $manager->switchActivation();
}

但是我不明白为什么当我触发原始函数getUser()时,存根方法updateNewsletter()(在switchActivation()中调用)会返回null

function switchActivation() : Company
{
    $this->company = $this->company->setActive(!$this->company->isActive());
    $this->company->save();
    $this->updateNewsletter();

    return $this->company;
}

这是未通过测试的功能

function updateNewsletter()
{
  $user = $this->company->getUser();
  // Do some other stuff...
}

1 个答案:

答案 0 :(得分:0)

代替

->willReturn($companyMock)

使用

->will($this->returnSelf())

Cf。 https://phpunit.readthedocs.io/en/7.4/test-doubles.html#test-doubles-stubs-examples-stubtest4-php