PHPUnit and die function

I use the phpunit framework and I have code like this:

public function A() { try { (...some code...) die (json_encode ($data)); } catch (Exception $e) { die(false); } } 

This function is called via AJAX, and I cannot replace die with a return. The question is: How can I do unit test with this code?

I can’t use for this, claims.

Thanks.

+8
php phpunit
source share
3 answers

You cannot check it ...

Unit testing sometimes causes such problems (unverifiable situations). This usually means that the problem is not in testing, but in the code and its architecture.

Here you should not use the die function (in fact you should not use die to return an HTTP response ), but echo json, and then let the script finish correctly (or return json and echo elsewhere).

To test this, you can capture the output and test it (this is a basic example, I think, much better).

Conclusion: there is a problem with your code, fix it, and then you can try testing it . If you cannot, then there is no testing.

+17
source share

Why can't you replace die() with return ?

My solution would be to throw this exception and then catch the exception using another method. Then you can unit test function a() by checking that it throws the correct kind of exception. Another function handles die() .

+3
source share

actually dying does not seem to be a good solution here. but if there is no way to change this, perhaps you can run the function in another process.

for this you need to write a test file that performs the function A. e.g.

 <?php include 'fileWithAFunction.php'; A(); ?> 

Now call this script with shell_exec.

 $return = shell_exec('testscript.php'); 

the returned variable contains the test result.

+3
source share

All Articles