使用phpspec在命令处理程序中测试工厂方法

时间:2015-06-30 14:14:13

标签: php testing static command phpspec

如何测试实际工厂方法的静态方法:

public function hireEmployee(HireEmployeeCommand $command)
{
    $username = new EmployeeUsername($command->getUsername());
    $firstName = $command->getFirstName();
    $lastName = $command->getLastName();
    $phoneNumber = new PhoneNumber($command->getPhoneNumber());
    $email = new Email($command->getEmail());
    $role = new EmployeeRole($command->getRole());

    if ($role->isAdmin()) {
        $employee = Employee::hireAdmin($username, $firstName, $lastName, $phoneNumber, $email);
    } else {
        $employee = Employee::hirePollster($username, $firstName, $lastName, $phoneNumber, $email);
    }

    $this->employeeRepository->add($employee);
}

在这里,我无法模拟Employee对象,但我可以为预期的员工模拟EmployeeRepository::add()方法,但我再次检查员工的状态:< / p>

public function it_hires_an_admin()
{
    $this->employeeRepository
        ->add(Argument::that(/** callback for checking state of Employee object */))
        ->shouldBeCalled();

    $this->hireEmployee(
        new HireEmployeeCommand(self::USERNAME, 'John', 'Snow', '123456789', 'john@snow.com', EmployeeRole::ROLE_ADMIN)
    );
}

我意识到我再次模拟了存储库而不是存根。但是在这里,我对员工更感兴趣的将被添加到存储库而不是如何创建它。因此,我应该模拟存储库,但我不应该关心Employee(没有Argument::that())的状态?看起来合理,但我不能确定创建的员工是否正确。

1 个答案:

答案 0 :(得分:3)

您并不需要存根或模拟您的实体或价值对象,因为它们在规范中没有表现出来:

public function it_hires_an_admin()
{
    $this->employeeRepository
        ->add(Argument::is(
            Employee::hireAdmin(self::USERNAME, 'John', 'Snow', '123456789', 'john@snow.com')
        ))
        ->shouldBeCalled();

    $this->hireEmployee(
        new HireEmployeeCommand(
            self::USERNAME, 'John', 'Snow', '123456789', 'john@snow.com', EmployeeRole::ROLE_ADMIN
        )
    );
}