Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit and die function

Tags:

php

phpunit

I'm using phpunit framework and I have a 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 can't replace die with return. The question is: How I can make a unit test with a code like this?

I can't use for this, the asserts.

Thanks.

like image 461
doctore Avatar asked May 09 '11 09:05

doctore


1 Answers

You can't test that...

Sometimes unit testing brings up problems like this (untestable situations). That usually means that the problem is not with the testing, but with your code and its architecture.

Here you shouldn't use the die function (actually you shouldn't use die to return a HTTP response), but echo the json and then let the script finish properly (or return the json and echo it somewhere else).

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

Conclusion : the problem is with your code, fix this and then you can try to test it. If you can't, then no testing.

like image 54
Matthieu Napoli Avatar answered Oct 07 '22 16:10

Matthieu Napoli