0

I'm working with PhpSpec and for some reason when I mock my dependencies and call them the willReturn method of PhpSpec give me a null value instead of the value passed.

This is the method that I'm trying to describe

    /**
     * Register an User
     *
     * @param array $infoUser
     * @return User
     */
    public function register(array $infoUser)
    {

        $user = $this->user->create($infoUser);

        $this->raise(new UserRegistered($user));

        return $user;
    }

My Spec

class BaseAuthSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Core\Auth\BaseAuth');
    }

    function let(AuthManager $guard,UserAuthRepository $user)
    {
        $this->beConstructedWith($guard,$user);
    }

    function it_register_an_user(UserAuthRepository $useRepo)
    {
        $user = [
            'username' => 'fabri',
            'email'    => 'test@test.com',
            'password' => 'password',
            'repeat_password' => 'password'
        ];

        $userModel = new User($user);

        // this line return null instead the $userModel
        $useRepo->create($user)->shouldBeCalled()->willReturn($userModel);

        $this->raise(new UserRegistered($userModel))->shouldReturn(null);

        $this->register($user)->shouldReturn($userModel);
    }
}

I'm stuck with this issue, any suggest will be appreciated.

4

1 回答 1

1

参数按名称匹配。let()传递给您的方法的用户存储库与传递给方法的用户存储库不同it_register_an_user()。要解决您的问题,只需将其命名为相同的名称。

您的规范中还有其他问题。

在您指定的类上模拟或存根方法是不可能的。这是行不通的:

$this->raise(new UserRegistered($userModel))->shouldReturn(null);

我不确定该raise()方法中发生了什么,但是您应该在示例中正确处理它,因此要么存根或模拟任何协作者(如果没有与当前示例相关的返回值,则不要理会它们)。

另一件事是,当您真正需要的是存根时,您会使用模拟。我会将您的示例重写为:

class BaseAuthSpec extends ObjectBehavior
{
    function let(AuthManager $guard, UserAuthRepository $userRepo)
    {
        $this->beConstructedWith($guard, $user);
    }

    function it_registers_a_user(UserAuthRepository $userRepo, User $userModel)
    {
        $user = [
            'username' => 'fabri',
            'email'    => 'test@test.com',
            'password' => 'password',
            'repeat_password' => 'password'
        ];

        $userRepo->create($user)->willReturn($userModel);

        $this->register($user)->shouldReturn($userModel);
    }
}

raise 方法应由单独的示例介绍。

于 2014-09-08T20:27:51.063 回答