testing exceptions with phpunit - php

i am trying to test a function when i know error i going to be thrown. the function looks like this:
function testSetAdsData_dataIsNull(){
$dataArr = null;
$fixture = new AdGroup();
try{
$fixture->setAdsData($dataArr);
} catch (Exception $e){
$this->assertEquals($e->getCode(), 2);
}
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
}
Now i am trying to use the phpunit exceptions assertions methods to replace the try catch part but i can't figure out how to do that.
i did lots of reading including this post PHPUnit assert that an exception was thrown? but i couldnt really understand how it shuold be implemented.
i tried something like this:
/**
* #expectedException dataIsNull
*/
function testSetAdsData_dataIsNull(){
$dataArr = null;
$fixture = new AdGroup();
$this->setExpectedException('dataIsNull');
$fixture->setAdsData($dataArr);
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
}
but obviously it didn't work and i got this error:
1) adGroupTest::testSetAdsData_dataIsNull
ReflectionException: Class dataIsNull does not exist
what am i doing wrong and how exactly can i assert if exception was thrown plz?

I generally use the #expectedException annotations for just such cases. See all exception-related annotations here:
/**
* #expectedException \Exception
* #expectedExceptionCode 2
*/
function testSetAdsData_dataIsNull()
{
$dataArr = null;
$fixture = new AdGroup();
$fixture->setAdsData($dataArr);
}
Checking that $fixture->ads is really null doesn't really add up here, you can add these asserts prior to the call that actually triggers an exception:
$this->assertNull($fixture->ads);
$fixture->setAdsData($dataArr);//throws exception
You're unit testing. This test serves a clear purpose: it makes sure an exception is thrown in a given situation. If it does, then that's where the test ends.
Still, if you want to keep those assertEmpty calls, you could do this:
try {
$fixture->setAdsData($dataArr);
$e = null;
} cathc (Exception $e) {}
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
if (!$e instanceof \Exception) {
//if the exception is not thát important:
$this->markTestIncomplete('No Exception thrown');
//do other stuff here... possibly
$this->fail('The exception was not thrown');
}
throw $e;//throw exception a bit later
An alternative approach would be to call $this->setExpectedException manually as explained here. Since we don't seem to know/care what the exception message will look like, I'm going to use the setExpectedExceptionRegExp method:
$fixture = new AdGroup();
$this->setExpectedExceptionRegExp(
//exception class, message regex, exception code
'Exception', '/.*/'. 2
);
$fixture->setAdsData(null);//passing null seems to be what you're doing anyway

Related

PHPUnit expect exception failing due to foreach warning

I want to test that a method called foo() throws an exception. The problem is that I can't get PHPUnit expectException() to catch the exception.
foo() looks something like this:
public function foo()
{
$params = $this->readAndFormatConfig();
// exception actually gets thrown in this method
$this->method->throws->exception($params);
}
If I catch the exception manually it works fine, like this:
public function testFoo()
{
$badConfig = new Config([]);
$driver = new bar($badConfig);
$exceptionThrown = false;
try {
$driver->foo();
} catch (Exception $e) {
$exceptionThrown = true;
}
$this->assertTrue($exceptionThrown);
}
If I catch it using expectException, like this:
public function testFoo()
{
$badConfig = new Config([]);
$driver = new bar($badConfig);
$this->expectException(Exception::class);
$driver->foo();
}
the test fails and I get this exception:
MyTestClass::testFoo Invalid argument supplied for foreach()
The output of get_class($e) is PHPUnit_Framework_Error_Warning which surprised me, but explains why the first test works but the second doesn't.
I'd like to either ignore the warning and wait until a real exception is thrown, or get the original warning, not PHPUnit_Framework_Error_Warning.
I'm using php 5.6.32 and PHPUnit 5.7.15
Adding the following to boostrap.php converts warnings to exceptions.
function warningToException($errno, $errstr, $errfile, $errline)
{
throw new Exception($errstr . " on line " . $errline . " in file " . $errfile);
}
set_error_handler("warningToException", E_WARNING);
This allowed the following test pass.
public function testFoo()
{
$badConfig = new Config([]);
$driver = new bar($badConfig);
$this->expectException(Exception::class);
$driver->foo();
}
I think a better method would be to expect PHPUnit_Framework_Error_Warning in the test as ishegg suggested.
What I ended up actually doing was making sure the object I was passing to foreach was traversable before entering the loop.
public function foo()
{
if (is_array($x) || $x instanceof \Traversable) {
// do stuff
} else {
// return false;
}
}
I think it makes more sense to refactor the application code in this case. What I'm really trying to test is that the function foo returns false if the application is misconfigured, so handling the misconfiguration properly seems like the right path in my opinion.
If you stumble upon this question for some reason and really need to convert warnings to an exception class other than PHPUnit_Framework_Error_Warning this is how I did it.
Thanks to ishegg for pointing me in the right direction.

executing assertions after exception is thrown using phpunit

i started using phpunit and came across this issue im wondering what is the best way to deal with it. I am testing the following function:
/**
* #expectedException PHPUnit_Framework_Error
*/
function testSetAdsData_dataIsNull()
{
$dataArr = null;
$fixture = new AdGroup();
$fixture->setAdsData($dataArr);
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
}
now the line $fixture->setAdsData($dataArr); throws an exception as i want and that's ok, but the problem is the following two assertions won't execute. so i read about it and understood that if i want to execute the two following assertions i need to use try/catch , so my question is,
what is the correct way to do that?
i tried doing this:
/**
* #expectedException PHPUnit_Framework_Error
*/
function testSetAdsData_dataIsNull()
{
$dataArr = null;
$fixture = new AdGroup();
try{
$fixture->setAdsData($dataArr);
} catch (Exception $e){
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
}
}
but now the exception is not thrown. should i leave it this way and just remove the expectation part from the top or is there a better way to do that?? thx
Yes, you need to get rid of the expectedException annotation. You're catching the exception so it won't be thrown now. Indeed, there is another problem: now, if the Exception is not thrown, the test will pass.
The solution is use a return sentence after the assertions, and making the test fail manually when the Exception is not thrown:
function testSetAdsData_dataIsNull()
{
$dataArr = null;
$fixture = new AdGroup();
try {
$fixture->setAdsData($dataArr);
} catch (Exception $e){
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
return;
}
$this->fail('Exception not thrown');
}
Another recommendation: use Exception subclasses. If an Exception is thrown but not for the reason you expect, the test will pass but maybe the behaviour is not the expected in the real code. If you catch only a certain type of exception, you will be sure that the Exception was raised for the right reason.

Simple Exception sample - PHP

I am trying to understand what the best approach would be to handle Exceptions in the following scenario:
I have a class employee:
class employee extends person {
private $salary;
private $baseSalary = 6.5;
function __construct($f, $m, $l, $a,$fsalary=0){
if(!is_numeric($fsalary)){
throw new Exception("Age supplied is not a number", 114);
}
parent::__construct($f, $m, $l, $a);
$this->salary=$fsalary;
}
function GetDetails(){
return parent::GetName().
"<br/>".
$this->salary;
}
function __toString(){
return $this->GetDetails();
}
}
And using this:
try{
if(!$f = new employee("Sarah", "Sebastian", "Pira", "abc")){
throw new Exception();
}
else {
echo $f;
}
}
catch (Exception $e){
echo "<br/>";
echo var_dump($e);
}
Now I would think it would be a good idea to throw an exception in the class and then use just one catch block in all the scripts that would be using an employee object - But this doesn't seem to work - I need to have a try catch block within the class - Is this the correct way of looking at this?
Thanks
I think what you're saying is that you want to do something like this:
try {
class Employee extends Person {
// ...blah blah...
}
}
catch(Exception $e) {
// handle exception
}
...and then be able to insantiate it in other classes, without explicitly catching any exceptions:
// try { << this would be removed
$employee = new Employee();
// }
// catch(Exception $e) {
// (a whole bunch of code to handle the exception here)
// }
You can't do that, because then the try/catch block in the class will only catch any exceptions that occur when defining the class. They won't be caught when you try to instantiate it because your new Employee line is outside the try/catch block.
So really, your problem is that you want to be able to re-use a try/catch block in multiple places without re-writing the code. In that case, your best solution is to move the contents of the catch block out to a separate function that you can call as necessary. Define the function in the Employee class file and call it like this:
try {
$employee = new Employee();
$employee->doSomeStuff();
$employee->doMoreStuffThatCouldThrowExceptions();
}
catch(Exception $e) {
handle_employee_exception($e);
}
It doesn't get rid of the try/catch block in every file, but it does mean that you don't have to duplicate the implementation of the exception-handling all the time. And don't define handle_employee_exception as an instance method of the class, do it as a separate function, otherwise it will cause a fatal error if the exception is thrown in the constructor because the variable won't exist.
You should read more about Exceptions in PHP.
You can handle exceptions within the methods of the class, sure. But you should rethink how you want to do this and... why.
Good practice is also creating own exception class, so you are able to distinguish exceptions thrown by your module / class from the exceptions thrown by something else. It looks like that (see more):
class EmployeeModule_Exception extends Exception {}
and when it comes to throwing exception:
// the second parameter below is error code
throw new EmployeeModule_Exception('some message', 123);
Catching is similar, only the below example will catch only your module's exceptions:
try {
// some code here
} catch (EmployeeModule_Exception $e) {
// display information about exception caught
echo 'Error message: ' . $e->getMessage() . '<br />';
echo 'Error code: ' . $e->getCode();
}

Better way of error handling?

What are best way of error handling? This is what I came up with:
class test {
public static function Payment($orderid, $total) {
if (empty($orderid) && empty($total)) {
return array('status' => 'fail', 'error' => 'Missing Data');
}
}
}
I heard about Try/Exceptions but how to fit that into my code? If you could provide example that would be great!
If you use PHP 5, you can handle error with exception :
http://fr2.php.net/manual/en/class.exception.php
This way is cleaner than manual set exception message, because you have access to a try catch system and you can isolate exception handling
As mentioned, use Exceptions. Specific to your example, you throw an exception if some condition fails. Then when you envoke the method that can throw an exception, you wrap it with a try/catch handling block.
class test {
public static function Payment( $orderid, $total ) {
if (empty( $orderid ) && empty( $total )) {
throw new Exception('Missing Data');
}
}
}
try {
test::Payment("1", "2"); //should be fine
test::Payment(); //should throw exception
} catch (Exception $e){
echo $e;
//do other things if you need
}
You could use exceptions.
However, in the use case you've posted, simply doing the checks at the controller level should suffice.
I also think that explicitly checking the return type for array (on fail) is counter intuitive.
Here is how you might modify your code to use an exception. It also helps to document the circumstances under which the exception is thrown.
class test {
/**
* [method description]
* #throws Exception if the order ID or total is empty
*/
public static function Payment($orderid, $total) {
if (empty($orderid) && empty($total)) {
throw new Exception("fail: Missing Data");
}
}
}
You can also create your own exception class if you want to include extra data in the exception.
class MyException extends Exception{
public $status, $error;
public function __construct($status, $error){
parent::__construct("$status: $error");
$this->status = $status;
$this->error = $error;
}
}
I tend to lean towards throwing exceptions, and then using the try/catch mechanism to deal with the aftermath. The man page is here: http://php.net/manual/en/language.exceptions.php
The best practice is to use Exceptions.
http://php.net/manual/en/language.exceptions.php

SimpleTest: How to assert that a PHP error is thrown?

If I am correct, SimpleTest will allow you to assert a PHP error is thrown. However, I can't figure out how to use it, based on the documentation. I want to assert that the object I pass into my constructor is an instance of MyOtherObject
class Object {
public function __construct(MyOtherObject $object) {
//do something with $object
}
}
//...and in my test I have...
public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
$notAnObject = 'foobar';
$object = new Object($notAnObject);
$this->expectError($object);
}
Where am I going wrong?
Type hinting throws E_RECOVERABLE_ERROR which can be caught by SimpleTest since PHP version 5.2. The following will catch any error containing the text "must be an instance of". The constructor of PatternExpectation takes a perl regex.
public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
$notAnObject = 'foobar';
$this->expectError(new PatternExpectation("/must be an instance of/i"));
$object = new Object($notAnObject);
}
PHP has both errors and exceptions, which work slightly different. Passing a wrong type to a typehinted function will raise an exception. You have to catch that in your test case. Eg.:
public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
$notAnObject = 'foobar';
try {
$object = new Object($notAnObject);
$this->fail("Expected exception");
} catch (Exception $ex) {
$this->pass();
}
}
or simply:
public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
$this->expectException();
$notAnObject = 'foobar';
$object = new Object($notAnObject);
}
But note that this will halt the test after the line where the exception occurs.
Turns out, SimpleTest doesn't actually support this. You can't catch Fatal PHP errors in SimpleTest. Type hinting is great, except you can't test it. Type hinting throws fatal PHP errors.
you have to expect the error before it happens, then SimpleTest will swallow it and count a pass, if the test gets to the end and there is no error then it will fail. (there's expectError and expectException that act in the same way, for PHP (non-fatal) errors and Exceptions, respectively.)

Categories