【问题标题】:Testing factory method in command handler with phpspec使用 phpspec 在命令处理程序中测试工厂方法
【发布时间】:2015-06-30 14:14:13
【问题描述】:

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

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() 方法,然后我再次检查员工的状态:

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 是否正确。

【问题讨论】:

    标签: php testing static command phpspec


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 2015-02-14
      • 2010-11-09
      相关资源
      最近更新 更多