1

我在帮助文件中创建了一个包装函数来包装全局使用的方法,例如 getTimestamp()。帮助文件与我正在测试的文件(“模型文件”)放在相同的命名空间中,即“Project\Models\TeamName”之类的命名空间。假设的模型文件使用 getTimestamp() 函数并进行计算以检查出生年份。我想在计算中测试边缘情况,因此我覆盖了“getTimestamp()”函数以始终在帮助文件中返回 125。

但是,这会导致其他使用 getTimpestamp() 的phpunit 测试失败。我怎样才能把它拆掉,这样我的帮助文件的'require_once'就被撤消了,所以其余的phpunit测试通过了?phpunit 测试类和 SUT 位于很远的命名空间中。

现在我有一个 PHPUnit 类(位于 Project\Testing\PHPUnit\Models\TeamName)

namespace Project\Testing\PHPUnit\Models\TeamName;
require_once '/testing/phpunit/models/teamname/testHelper.php';

use Project\Models\TeamName\MyModel

class MyModelTest {
    const correctAge = 75; 

    public function testAge(){
        $model = new MyModel(); 
        $result = $model -> calculateAgeFromBirthYear(50);
        assertEquals(self::correctAge, $result); 
    }
}

以及帮助文件(位于 Project\Testing\PHPUnit\Models\TeamName 中)

namespace Project\Models\TeamName; 
function getTimestamp(){
    //today is year 125
    return 125; 
}

以及 SUT/模型(位于 Project\Models\TeamName)

namespace Project\Models\TeamName; 
class MyModel {
    function calculateAgeFromBirthYear($birthYear){
        $date = new DateTime();
        $today = $date->getTimestamp(); 
        return $today - $birthYear;
    }
}

我不希望其他 phpunit 类继承始终返回 125 的 getTimestamp(),我想撤消 requires_once

4

1 回答 1

0

所以这对我来说是有效的,不一定是每个案例。

在 MyModel 类中,我放置了一个名为“getTimestampWrapper”的函数,该函数随后称为“getTimestamp”,没有其他任何操作。我的 calculateAgeFromBirthYear 函数现在看起来像这样:

namespace Project\Models\TeamName; 
class MyModel {
    function calculateAgeFromBirthYear($birthYear){
        $today = getTimestampWrapper(); 
        return $today - $birthYear;
    }
    function getTimestampWrapper(){
        $date = new DateTime();
        $todayWrapper = $date->getTimestamp(); 
        return $todayWrapper;
    }
}

在 MyModelTest 中,我模拟了 MyModel 对象,然后使用 onConsecutiveCalls 来正确预期结果。

  //make sure a function called 'getTimestampWrapper' is in your model
  $model = $this->getMockBuilder(MyModel::class)
      ->setMethods('getTimestampWrapper')
      ->getMock();

  //my onConsecutiveCalls will get me the fake timestamps I want
  $model  ->method('getTimestampWrapper')
      ->will(
          $this->onConsecutiveCalls(...[125, 125, 100])
      );
  //run your assertEquals now

所以现在当我在单元测试中调用 $model->calculateAgeFromBirthYear(50) 时,它会调用 use 125, 125, 100 作为时间戳

于 2019-07-24T15:06:04.657 回答