-3

I created register service and I want test that method. In the browser var_dump return true and phpspec return false.. Why ? Any Ideas?

Service : http://pastebin.com/9hYX7S14 Phpspec : http://pastebin.com/xm5NLYyG

Please help.

Matrix12
  • 446
  • 8
  • 19

2 Answers2

1

You need to stub (or mock) all your dependencies:

    function it_check_user_exist_in_system(
        Registry $doctrine, 
        ObjectRepository $repository,
        User $user
    )
    {
        $doctrine->getManager()->willReturn($doctrine);
        $doctrine->getRepository('AcmeUserBundle:User')->willReturn($repository)

        $repository->findOneBy(array('username'=>'user1'))->willReturn($user);

        $this->checkUser('user1')->shouldReturn(true);
    }
gvf
  • 1,039
  • 7
  • 6
  • If repository found user1 return true, but if repository not found user2 return true.. what's wrong ? – Matrix12 Aug 30 '15 at 14:07
  • In that case: function it_returns_false_if_user_not_found( Registry $doctrine, ObjectRepository $repository ) { $doctrine->getManager()->willReturn($doctrine); $doctrine->getRepository('AcmeUserBundle:User')->willReturn($repository) $repository->findOneBy(array('username'=>'user1'))->willReturn(null); $this->checkUser('user1')->shouldReturn(false); } – gvf Aug 30 '15 at 16:05
  • Thanks bro. Works :) I forget about willReturn(null) ; :) – Matrix12 Aug 30 '15 at 17:24
  • If my answer was helpful please select it. Thanks. – gvf Aug 31 '15 at 11:19
  • Ok. Last question. I try test peresit layer, whether my service save user. Spec give me 100% but with error Call to undefined method Prophecy\Prophecy\MethodProphecy::persist() Me test is correct or fail why? http://pastebin.com/ua87hRJK – Matrix12 Sep 01 '15 at 15:57
  • getManager should return a manager not a Registry: $doctrine->getManager()->willReturn($entityManager); and then $entityManager->persist($site)->shouldBeCalled(); and same for persist. – gvf Sep 01 '15 at 16:00
  • I can't see that option.. ;/ – Matrix12 Sep 01 '15 at 17:34
0

You're trying to get the result from a Mocked object.

You're best bet for testing this method is to test using a should be called assertion on the mocked object.

This is not a unit test its functional/acceptance test.

nathanmac
  • 455
  • 1
  • 6
  • 14
  • Why isn't a unit test? It's part of service, so should be unit. – Matrix12 Aug 30 '15 at 13:45
  • 1
    Here your SUS is ``RegisterTest`` class, you are testing it's behavious therefore you have to ``simulate`` it's collaborators. If you need to test a service, then it's not a unit test, as nathanmac said, it would be a functional/acceptance and I would suggest using Behat for that. – gvf Aug 30 '15 at 16:04