joeyadms
joeyadms

Reputation: 95

PHPUnit stub throws exception but isn't allowed to be caught

I'm trying to test a try/catch block using a stub that throws an exception when a certain method create is called. It works fine, the exception is raised, but instead of my application catching it, it stops the execution of the test. What is some better ways to go about doing this.

<?php
// TestCase
        $mockDao->expects($this->once())
                ->method('create')
                ->will($this->throwException(new \Exception));

        $service->addEntity($data);
?>


<?php
// Service
    public function addEntity($data)
    {
           ....

        try {
               ...
            $this->create($entity); // Test Halts with Exception
               ...
        } catch (Exception $e) {
           // Never Gets Called
           $this->handleException($e);
        }
    }

Upvotes: 8

Views: 3213

Answers (1)

David Harkness
David Harkness

Reputation: 36532

You are throwing \Exception but catching Exception. Is the class that implements addEntity() in a namespace? Does changing it to catch \Exception fix the problem? If not, try changing the test to throw Exception.

Upvotes: 8

Related Questions