使用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()方法,但随后我将再次检查employee:的状态

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())的状态?看起来很合理,但我不能确定创建的Employee是否正确。

您实际上不需要存根或模拟实体或值对象,因为它们在规范中没有表现出任何行为:

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
        )
    );
}

相关内容

  • 没有找到相关文章

最新更新