使用phpspec在命令处理程序中测试工厂方法 [英] Testing factory method in command handler with phpspec

查看:178
本文介绍了使用phpspec在命令处理程序中测试工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试静态方法,它是infact的工厂方法:

How to test static methods which are infact factory methods:

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 object,但我可以为预期的员工模拟 EmployeeRepository :: add()方法,但是我再次检查Employee的状态: / p>

Here I can't mock the Employee object, but I can mock the EmployeeRepository::add() method for the expected employee but then I'm again checking the state of the 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)
    );
}


$ b $ p我知道我再次嘲笑了仓库,而不是存根。但是在这里我更感兴趣的是employee将被添加到仓库而不是如何创建它。因为我应该模拟存储库,但我不应该关心 Employee (没有 Argument :: that())?看起来合理,但是我不能确定创建的Employee是否正确。

I'm aware that again I mocked the repository instead of stub it. But here I'm more interested in employee will be added to the repository instead of how it would be created. Because of that I should mock the repository but I shouldn't care about the state of the Employee (without Argument::that())? Looks reasonable, but then I can't be sure that the created Employee is correct.

推荐答案

stub也不会模拟你的实体或值对象,因为它们没有在规范中显示的行为:

You don't really need to stub nor mock your entities or value objects, as there's no behaviour they exhibit in the spec:

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

这篇关于使用phpspec在命令处理程序中测试工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆