Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

phpunit

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);
        }
    }
like image 520
joeyadms Avatar asked Apr 19 '11 15:04

joeyadms


1 Answers

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.

like image 89
David Harkness Avatar answered Oct 10 '22 06:10

David Harkness