PHP单元测试来自不同类

时间:2015-11-06 02:23:59

标签: php unit-testing testing phpunit

我正在尝试为一个函数编写一个单元测试,该函数立即从另一个类中加载一个对象,该类使用该函数的输入作为参数。我是php单元测试的新手,无法找到解决我特定问题的任何东西。我所拥有的一些导致无用的是使用注射器,并尝试反射。

我正在尝试编写单元测试的代码是:

public static function isUseful($item) {

  $objPromo = MyPromoCodes::Load($item->SavedSku);

  if (!is_null($objPromo)
    && ($objPromo->PromoType == MyPromoCodes::Interesting_Promo_Type)) {
    return true;
  }
  return false;
}

我试图嘲笑这个:

public function testIsUseful() {

  $injector = $this->getMockBuilder('MyPromoCodes')
    ->setMethods(array('Load'))
    ->getMock();
  $objPromo = $this->getMock('MyPromoCodes');
  $objPromo->PromoType = 'very interesting promo type';
  $injector->set($objPromo, 'MyPromoCodes');

  $lineItem1 = $this->getDBMock('LineItem');


  $this->assertTrue(MyClass::isUseful($lineItem1));

}

但是这不起作用,因为此对象没有set方法....

不确定还有什么可以尝试,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

我使the library使静态类模拟成为可能:

[B = (1/2)*sqrt(2), C = (1/2)*sqrt(2), c = 45]

答案 1 :(得分:0)

首先,您不能使用PHPUnit模拟静态方法。至少不是4.x和5.x。

我建议像这样的DI方法:

class MyClass
{
    private $promoCodesRepository;

    public function __construct(MyPromoCodesRepository $promoCodesRepository)
    {
        $this->promoCodesRepository = $promoCodesRepository;
    }

    public function isUseful(MyItem $item)
    {
        $objPromo = $this->promoCodesRepository->Load($item->SavedSku);

        // ...
    }
}

在这里,您可以轻松模拟Load方法。

不幸的是,“静态”方法在测试期间会产生很多问题,因此最好尽可能避免使用它。

相关问题