Search code examples
unit-testingphpunitprivate-memberstest-coverage

PHPUnit testing an exception flow of execution


I guess this is a common problem but I am unable to decide how to solve this.

I have a public function that has 4 catch blocks. Inside each catch block one of the private methods is called as below

public function updateInformation(){

 try{
    .....
  }catch(Zend_Http_Client_Exception $e){
    $this->somePrivateMethod1();
  }catch(Zend_Service_Exception $e){
    $this->somePrivateMethod2();
  }catch(UnexpectedValueException $e){
    $this->somePrivateMethod3();
  }catch(Exception $e){
    $this->somePrivateMethod4();
  }

}

I am writing test case to test the updateInformation() function. I would like to test the exception blocks too which would let me test the private methods(too). How do I achieve this? Because of this the code coverage is also gone for a toss.


Solution

  • You have one of your dependencies throw the Exception so that your code will catch it.

    http://phpunit.de/manual/current/en/phpunit-book.html#test-doubles.stubs.examples.StubTest8.php

    public function testThrowExceptionStub()
        {
            // Create a stub for the SomeClass class.
            $stub = $this->getMock('SomeClass');
    
            // Configure the stub.
            $stub->method('doSomething')
                 ->will($this->throwException(new Exception));
    
            $sut = new Class($stub);
    
            $sut->updateInformation();
    
            //DO MORE ASSERTIONS ABOUT BEHAVIOR IN PRIVATE METHODS
    
        }
    }
    

    I am assuming that there is something in the try block that will need to be mocked. If there isn't then you set the class up so that the conditions are met such that the exceptions will be thrown.