How to output in CLI during execution of PHP Unit tests? - php

When running a PHPUnit test, I would like to be able to dump output so I can debug one or two things.
I have tried the following (similar to the PHPUnit Manual example);
class theTest extends PHPUnit_Framework_TestCase
{
/**
* #outputBuffering disabled
*/
public function testOutput() {
print_r("Hello World");
print "Ping";
echo "Pong";
$out = "Foo";
var_dump($out);
}
}
With the following result:
PHPUnit #package_version# by Sebastian Bergmann.
.
Time: 0 seconds, Memory: 3.00Mb
OK (1 test, 0 assertions)
Notice there is none of the expected output.
I'm using the HEAD versions of the git repos as of September 19th, 2011.
Output of php -version:
$ php -version
PHP 5.2.9 (cli) (built: Dec 8 2010 11:36:37)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies
with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans
Is there anything I'm doing wrong, or is this potentially a PHPUnit bug?

UPDATE
Just realized another way to do this that works much better than the --verbose command line option:
class TestSomething extends PHPUnit_Framework_TestCase {
function testSomething() {
$myDebugVar = array(1, 2, 3);
fwrite(STDERR, print_r($myDebugVar, TRUE));
}
}
This lets you dump anything to your console at any time without all the unwanted output that comes along with the --verbose CLI option.
As other answers have noted, it's best to test output using the built-in methods like:
$this->expectOutputString('foo');
However, sometimes it's helpful to be naughty and see one-off/temporary debugging output from within your test cases. There is no need for the var_dump hack/workaround, though. This can easily be accomplished by setting the --verbose command line option when running your test suite. For example:
$ phpunit --verbose -c phpunit.xml
This will display output from inside your test methods when running in the CLI environment.
See: Writing Tests for PHPUnit - Testing Output.

Try using --debug
Useful if you're trying to get the right path to an include or source data file.

Update: See rdlowrey's update below regarding the use of fwrite(STDERR, print_r($myDebugVar, TRUE)); as a much simpler work around
This behaviour is intentional (as jasonbar has pointed out). The conflicting state of the manual has been reported to PHPUnit.
A work-around is to have PHPUnit assert the expected output is empty (when infact there is output) which will trigger the unexpected output to be shown.
class theTest extends PHPUnit_Framework_TestCase
{
/**
* #outputBuffering disabled
*/
public function testOutput() {
$this->expectOutputString(''); // tell PHPUnit to expect '' as output
print_r("Hello World");
print "Ping";
echo "Pong";
$out = "Foo";
var_dump($out);
}
}
gives:
PHPUnit #package_version# by Sebastian Bergmann.
F
Time: 1 second, Memory: 3.50Mb
There was 1 failure:
1) theTest::testOutput
Failed asserting that two strings are equal.
--- Expected
+++ Actual
## ##
-''
+'Hello WorldPingPongstring(4) "Foo"
+'
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
Be certain to disable any other assertions you have for the test as they may fail before the output assertion is tested (and hence you wont see the output).

It's not a bug, but very much intentional. Your best bet is to write to a log file of some kind and tail the log to watch for output.
If you are trying to TEST output, check this out.
Also:
Note: Please note that PHPUnit swallows all output that is emitted
during the execution of a test. In strict mode, a test that emits
output will fail.

Just call ob_flush() after outputting text
Example code:
public function testDebugOutputToCli() {
var_dump(new DateTime());
ob_flush();
}
Screenshot of code and output:
Why? PHPUnit is always output buffering, so we need to dump the buffer when debugging
I was struggling with all the answers above, especially because the selected answer –using codecept_debug() with --debug as the manual says– caused a huge wave of debug output that made it impossible to use for me.
I was reading the PHPUnit manual like a good nerd and stumbled onto this, which I think explains what causes this whole issue across all of PHPUnit, not just Codeception:
PHPUnit manual, Testing Output: “Sometimes you want to assert that the execution of a method, for instance, generates an expected output (via echo or print, for example). The PHPUnit\Framework\TestCase class uses PHP’s Output Buffering feature to provide the functionality that is necessary for this.”
This makes total sense and explains why we don't see the output. PHPUnit is saving it up in case we want to examine the comments! This is how it should always work in our actual tests, we of course don't want random stuff getting to the screen just because we called a function that uses echo.
But when we're debugging, we just want to see the text right away, and understanding all this, the solution is clear: Just use ob_flush() to print the contents of the output buffer on demand!
Three cheers for reading the fun manuals!
P.S. Also found this tip hidden in How to show var_dumps in phpunit or codeception by Julian on dev.to

You should really think about your intentions: If you need the information now when debugging to fix the test, you will need it next week again when the tests break.
This means that you will need the information always when the test fails - and adding a var_dump to find the cause is just too much work. Rather put the data into your assertions.
If your code is too complex for that, split it up until you reach a level where one assertion (with a custom message) tells you enough to know where it broke, why and how to fix the code.

I'm having some luck with VisualPHPUnit, and it does helpfully show output, among other things.
class TestHello extends PHPUnit_Framework_TestCase
{
public function test_Hello()
{
print "hello world";
}
}

Just use the --verbose flag when execute phpunit.
$ phpunit --verbose -c phpunit.xml
The advantage of this method is that you don't need to change the test code, you can print strings, var_dump's o anything you wish always and it will be shown in the console only when verbose mode is set.
I hope this helps.

In laravel 5 you can use dump(), Dump the content from the last response.
class ExampleTest extends TestCase{
public function test1()
{
$this->post('/user', ['name' => 'Gema']);
$this->dump();
}
}
gives

This was taken from PHPUnit Docs about Fixtures.
This should allow you to dump information at any point durring the phpunit test life cycle.
Just replace __METHOD__ in the code below with whatever you want to output
Example 4.2: Example showing all template methods available
<?php
class TemplateMethodsTest extends PHPUnit_Framework_TestCase
{
public static function setUpBeforeClass()
{
fwrite(STDOUT, __METHOD__ . "\n");
}
protected function setUp()
{
fwrite(STDOUT, __METHOD__ . "\n");
}
protected function assertPreConditions()
{
fwrite(STDOUT, __METHOD__ . "\n");
}
public function testOne()
{
fwrite(STDOUT, __METHOD__ . "\n");
$this->assertTrue(TRUE);
}
public function testTwo()
{
fwrite(STDOUT, __METHOD__ . "\n");
$this->assertTrue(FALSE);
}
protected function assertPostConditions()
{
fwrite(STDOUT, __METHOD__ . "\n");
}
protected function tearDown()
{
fwrite(STDOUT, __METHOD__ . "\n");
}
public static function tearDownAfterClass()
{
fwrite(STDOUT, __METHOD__ . "\n");
}
protected function onNotSuccessfulTest(Exception $e)
{
fwrite(STDOUT, __METHOD__ . "\n");
throw $e;
}
}
?>

PHPUnit is hiding the output with ob_start(). We can disable it temporarily.
public function log($something = null)
{
ob_end_clean();
var_dump($something);
ob_start();
}

For some cases one could use something like that to output something to the console
class yourTests extends PHPUnit_Framework_TestCase
{
/* Add Warnings */
protected function addWarning($msg, Exception $previous = null)
{
$add_warning = $this->getTestResultObject();
$msg = new PHPUnit_Framework_Warning($msg, 0, $previous);
$add_warning->addWarning($this, $msg, time());
$this->setTestResultObject($add_warning);
}
/* Add errors */
protected function addError($msg, Exception $previous = null)
{
$add_error = $this->getTestResultObject();
$msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
$add_error->addError($this, $msg, time());
$this->setTestResultObject($add_error);
}
/* Add failures */
protected function addFailure($msg, Exception $previous = null)
{
$add_failure = $this->getTestResultObject();
$msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
$add_failure->addFailure($this, $msg, time());
$this->setTestResultObject($add_failure);
}
public function test_messages()
{
$this->addWarning("Your warning message!");
$this->addError("Your error message!");
$this->addFailure("Your Failure message");
}
/* Or just mark test states! */
public function test_testMarking()
{
$this->markTestIncomplete();
$this->markTestSkipped();
}
}

Hackish, but works: Throw an exception with the debug output as its message.
class theTest extends PHPUnit_Framework_TestCase
{
public function testOutput() {
throw new \Exception("hello");
}
}
Yields:
...
There was 1 error:
1) theTest::testOutput
Exception: hello

I output my Testresults HTML based, in this case it was helpfull to flush the content:
var_dump($array);
ob_flush();
There is a second PHP Method
flush()
which i not has tried.

It is possible to use Symfony\Component\Console\Output\TrimmedBufferOutput and then test the buffered output string like this:
use Symfony\Component\Console\Output\TrimmedBufferOutput;
//...
public function testSomething()
{
$output = new TrimmedBufferOutput(999);
$output->writeln('Do something in your code with the output class...');
//test the output:
$this->assertStringContainsString('expected string...', $output->fetch());
}

I had to modify source code for this code to work so you need to add URL for this forked repos to composer for this will work
class TestCase extends \PHPUnit_Framework_TestCase
{
/**
* Save last response
* #var Response|null A Response instance
*/
static $lastResponse;
/**
* Modify to save response
*
* #param string $method
* #param string $uri
* #param array $parameters
* #param array $files
* #param array $server
* #param string $content
* #param bool $changeHistory
* #return \Illuminate\Http\Response
*/
final public function call(
$method,
$uri,
$parameters = [],
$files = [],
$server = [],
$content = null,
$changeHistory = true
) {
$response = parent::call($method, $uri, $parameters, $files, $server, $content, $changeHistory);
static::$lastResponse = $this->client->getResponse();
return $response;
}
/**
* Modify message to add response text
*
* #param mixed $value
* #param PHPUnit_Framework_Constraint $constraint
* #param string $message
* #since Method available since Release 3.0.0
*/
final public static function assertThat($value, PHPUnit_Framework_Constraint $constraint, $message = '')
{
$message .= PHP_EOL . static::$lastResponse . PHP_EOL;
parent::assertThat($value, $constraint, $message);
}
}

Here are few methods useful for printing debug messages in PHPUnit 4.x:
syslog(LOG_DEBUG, "Debug: Message 1!");
More practical example:
syslog(LOG_DEBUG, sprintf("%s: Value: %s", __METHOD__, var_export($_GET, TRUE)));
Calling syslog() will generate a system log message (see: man syslog.conf).
Note: Possible levels: LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING, LOG_ERR, etc.
On macOS, to stream the syslog messages in realtime, run:
log stream --level debug --predicate 'processImagePath contains "php"'
fwrite(STDERR, "LOG: Message 2!\n");
Note: The STDERR constant is not available if reading the PHP script from stdin. Here is the workaround.
Note: Instead of STDERR, you can also specify a filename.
file_put_contents('php://stderr', "LOG: Message 3!\n", FILE_APPEND);
Note: Use this method, if you don't have STDERR constant defined.
register_shutdown_function('file_put_contents', 'php://stderr', "LOG: Message 4!\n", FILE_APPEND);
Note: Use this method, if you'd like to print something at the very end without affecting the tests.
To dump the variable, use var_export(), e.g. "Value: " . var_export($some_var, TRUE) . "\n".
To print above messages only during verbose or debug mode, see: Is there a way to tell if --debug or --verbose was passed to PHPUnit in a test?
Although if testing the output is part of the test it-self, check out: Testing Output docs page.

In short, phpunit supresses STDOUT. It writes to STDERR by default, unless you add --verbose or --debug . You can do one of those things:
print your debug output to STDERR instead
var_dump your debug as usual but add --verbose to the phpunit command line
var_dump your debug as usual but add a line ob_flush(); beneath it
use the correct commands in phpunit for testing exactly what you're trying to test here
Obviously, the last thing is the Good Thing to do, and the rest are quick temporary hacks.

You can use PHPunit default way of showing messages to debug your variables inside your test like this:
$this->assertTrue(false,$your_variable);

it's a paid product, but I find it does the job well: Ray from Spatie
https://spatie.be/products/ray
just use it like this:
ray('message')
and the message will show up in Ray output window

If you use Laravel, then you can use logging functions such as info() to log to the Laravel log file under storage/logs. So it won't appear in your terminal but in the log file.

Related

phpunit9 mocked method still being executed

I'm trying to mock a call to the Twilio Rest API for a test I'm writing. This is the code I've written to mock:
$message = $twilioTest->getMockedMessageInstance(['body' => 'This won\'t exist']);
$twilioStub = $this->getMockBuilder(Twilio::class)->getMock();
$twilioStub->expects($this->once())->method('retrieveLastTextFromBot')->willReturn($message);
And the contents of the retrieveLastTextFromBot method are:
$messages = $this->twilioClient->messages->read([
'to' => TwilioDefinitions::getToNumber(),
'from' => getenv('TWILIO_NUMBER'),
], 1);
if (count($messages) !== 1) {
throw new NoExtantTextException('No previous message from ' . getenv('TWILIO_NUMBER') . ' to ' . TwilioDefinitions::getToNumber());
}
return $messages[0];
But obviously, I don't want the contents of the retrieveLastTextFromBot method to execute, that's why I'm mocking it. For some reasons though, that method is executing, and I know that because in my phpunit failure I'm getting this error:
1) CronControllerTest::testRemindMethodErrorHandling
Twilio\Exceptions\RestException: [HTTP 403] Unable to fetch page: Resource not accessible with Test Account Credentials
/Users/adammcgurk/Desktop/ymca-scheduler-brains/src/vendor/twilio/sdk/src/Twilio/Page.php:58
/Users/adammcgurk/Desktop/ymca-scheduler-brains/src/vendor/twilio/sdk/src/Twilio/Page.php:34
/Users/adammcgurk/Desktop/ymca-scheduler-brains/src/vendor/twilio/sdk/src/Twilio/Rest/Api/V2010/Account/MessagePage.php:23
/Users/adammcgurk/Desktop/ymca-scheduler-brains/src/vendor/twilio/sdk/src/Twilio/Rest/Api/V2010/Account/MessageList.php:147
/Users/adammcgurk/Desktop/ymca-scheduler-brains/src/vendor/twilio/sdk/src/Twilio/Rest/Api/V2010/Account/MessageList.php:96
/Users/adammcgurk/Desktop/ymca-scheduler-brains/src/vendor/twilio/sdk/src/Twilio/Rest/Api/V2010/Account/MessageList.php:118
/Users/adammcgurk/Desktop/ymca-scheduler-brains/src/app/YmcaScheduler/Utility/Twilio.php:33
/Users/adammcgurk/Desktop/ymca-scheduler-brains/src/app/YmcaScheduler/Controller/CronController.php:29
/Users/adammcgurk/Desktop/ymca-scheduler-brains/tests/CronControllerTest.php:22
And line 33 in Twilio.php is that fourth line of the retrieveLastTextFromBot() method, so it's executing.
And maybe I just understand mocking incorrectly, but what I thought was going to happen was the method wouldn't be executed at all, instead, phpunit would just force data to be returned from it.
How can I mock a method in phpunit without it actually being executed?
Working example
I start this answer with a working example. There are two things you can check as explained in this answer. Please update your question with extra information/ details when parts of the answer fit your situation.
Add this code to tests/TwilioTest.php:
<?php
use PHPUnit\Framework\TestCase;
use Twilio\Rest\Client;
class Twilio
{
private $twilioClient;
public function __construct(Client $twilioClient)
{
$this->twilioClient = $twilioClient;
}
public function retrieveLastTextFromBot()
{
$messages = $this->twilioClient->messages->read([
'to' => TwilioDefinitions::getToNumber(),
'from' => getenv('TWILIO_NUMBER'),
], 1);
if (count($messages) !== 1) {
throw new NoExtantTextException('No previous message from ' . getenv('TWILIO_NUMBER') . ' to ' . TwilioDefinitions::getToNumber());
}
return $messages[0];
}
}
class Sut
{
private $twilio;
public function __construct(Twilio $twilio)
{
$this->twilio = $twilio;
}
public function method()
{
$this->twilio->retrieveLastTextFromBot();
}
}
final class TwilioTest extends TestCase
{
//I created a plain php object for the message just for the example
private function getMockedMessageInstance(array $message)
{
return (object) $message;
}
public function test_sut_method(): void
{
$message = $this->getMockedMessageInstance(['body' => 'This won\'t exist']);
$twilioStub = $this
->getMockBuilder(Twilio::class)
->disableOriginalConstructor() # I have added this to ignore the Twilio constructor dependencies
->getMock();
$twilioStub->expects($this->once())->method('retrieveLastTextFromBot')->willReturn($message);
$sut = new Sut($twilioStub);
$result = $sut->method();
}
}
Result
Execute the tests:
vendor/bin/phpunit tests/
Please verify if this code is working for you also. If not, please tell me what composer library versions you use. Consider adding this info to your question composer show -i.
The result should be:
PHPUnit 9.5.21 #StandWithUkraine
. 1 / 1 (100%)
Time: 00:00.006, Memory: 4.00 MB
OK (1 test, 1 assertion)
I expect you somehow call retrieveLastTextFromBot on something else than the mock object
If the code above is working, I suspect you somehow call the method retrieveLastTextFromBot on the production code, instead of the mock object or you might execute the method twice from a different location.
To find out what is really happening add the following code to retrieveLastTextFromBot (in your production code):
public function retrieveLastTextFromBot()
{
var_dump(debug_backtrace()[0]['file']); # This line
var_dump(debug_backtrace()[0]['line']); # This line
exit; # This line
$messages = $this->twilioClient->messages->read([
'to' => TwilioDefinitions::getToNumber(),
'from' => getenv('TWILIO_NUMBER'),
], 1);
if (count($messages) !== 1) {
throw new NoExtantTextException('No previous message from ' . getenv('TWILIO_NUMBER') . ' to ' . TwilioDefinitions::getToNumber());
}
return $messages[0];
}
If it returns the file where the SUT (System under test) is located, you now know for sure you don't have executed the method on the mock object. You might see a different file, in that case, check your code to see from where you execute it.
Check your tests to see what instance is passed in the constructor. If otherwise, let me know what the result of the debug_backtrace() is and consider updating your question with the results so we can continue to help, since not all code is provided it might be needed to help your further.
If non of the previous explained tests gave you enough information, please consider adding a temporarily github repository with your code and maybe if possible some test environment credentials.

How do I verify that this function is a string in PHPUnit?

Here's the code for my original PHP code:
public function outputText() {
$i = 1;
foreach($this->sorted_data as $this->data) {
echo "$i. ".$this->data[0]."<br/>";
$i++;
}
}
And here's the code for the PHPUnit:
public function testVerify() {
$yn = new SortThisData();
$yn->readFile("input.txt");
$output = $yn->outputText();
$this->assertTrue(is_string($output));
//if(!is_string($yn->get()))
// return false;
//$this->assertNotEmpty($yn->get());
}
The class is called SortThisData in the original PHP file.
When I used gettype(), it said it was null. I'm trying to verify that it is a string so it can pass in PHPUnit. Is there a way I can do this?
You're looking for assertInternalType().
Update: I didn't realize you were echoing the output. You will probably need to use output buffering to capture the text.
public function testVerify() {
$yn = new SortThisData();
$yn->readFile("input.txt");
// start output buffering and capture the output
ob_start();
$yn->outputText();
$output = ob_get_clean();
$this->assertInternalType('string', $output);
}
No disagreement with Baylor's answer. To answer the question, as asked, what you had was also good enough:
$this->assertTrue(is_string($output));
Or you could have done:
$this->assertEquals('string',gettype($output));
(The advantage of the latter is, when it fails, it will also tell you the type of $output; assertTrue will only tell you that something failed.)
assertInternalType() does exactly that, but was only introduced in PHPUnit 3.5, and you will still find PHPUnit 3.4 in use on some machines.

PHPUnit and SplFileObject returning true isWritable on read-only object

I have a Logger interface that accepts a SplFileObject in the constructor to use as the file for that particular log. There is also a log($timestamp, $message) method available to actually do the logging. In my first implementation when instantiating a new object and passing a read-only SplFileObject an exception should be thrown. I wrote up an appropriate unit test:
<?php
class FileLoggerTest extends PHPUnit_Framework_TestCase {
/**
* #expectedException \InvalidArgumentException
*/
public function testReadOnlyFileObjectFailure() {
$file = '/Library/WebServer/Documents/sprayfire/tests/mockframework/logs/test-log.txt';
$LogFile = new \SplFileObject($file);
$Logger = new \libs\sprayfire\logger\FileLogger($LogFile);
$Logger->log('test', 'something');
}
}
?>
Normally I would have a method producing the directory name but when I started encountering problems I changed it to an absolute path to rule out that as the cause.
And here's the implementation:
namespace libs\sprayfire\logger;
use \SplFileObject as SplFileObject;
use \InvalidArgumentException as InvalidArgumentException;
use libs\sprayfire\logger\Logger as Logger;
/**
* #brief A framework implemented class that adds a timestamp log message to
* the end of an injected file.
*/
class FileLogger implements Logger {
/**
* #brief A SplFileObject that should be used to write log messages to.
*
* #property $LogFile
*/
protected $LogFile;
/**
* #param $LogFile SplFileObject that should have log messages written to
*/
public function __construct(SplFileObject $LogFile) {
$this->LogFile = $LogFile;
$this->throwExceptionIfFileNotWritable();
}
/**
* #throws InvalidArgumentException
*/
protected function throwExceptionIfFileNotWritable() {
$isWritable = $this->LogFile->isWritable();
if (!$isWritable) {
throw new InvalidArgumentException('The passed file, ' . $this->LogFile->getPathname() . ', is not writable.');
}
}
/**
* #param $timestamp A formatted timestamp string
* #param $message The message string to log
* #return boolean true if the message was logged, false if it wasn't
*/
public function log($timestamp, $message) {
if (!isset($timestamp) || empty($timestamp)) {
$timestamp = 'No timestamp given';
}
if (!isset($message) || empty($message)) {
$message = 'Attempting to log an empty message';
}
$separator = ' := ';
$message = $timestamp . $separator . $message;
$wasWritten = $this->LogFile->fwrite($message);
if (!isset($wasWritten)) {
return false;
}
return true;
}
}
// End FileLogger
The problem is that the test passes and I can tell by the code coverage generated by the test that isWritable() returns true and SplFileObject::fwrite() on a readonly object returns a non-null value as well.
The really, really weird part of this is that the very same code ran in a non-unit test example fails, just as it should.
$logFile = '/Library/WebServer/Documents/sprayfire/tests/mockframework/logs/test-log.txt';
$SplFile = new \SplFileObject($logFile);
$Logger = new \libs\sprayfire\logger\FileLogger($SplFile);
Running this from index.php results in xdebug showing an uncaught InvalidArgumentException from FileLogger with the expected message that the file passed is not writable. This is completely baffling, the same exact code is being ran in both situations, yet the code inside the unit test is "failing" and the non-unit tested code is performing as expected.
Yes, the file exists. SplFileObject would throw an exception if it didn't.
The very exact same code is being ran in both situations, other code that is being ran includes setting up 2 constants, a file directory and a shortcut to DIRECTORY_SEPARATOR, and setting up class autoloading. But, again, this is happening exactly the same in both situations and would result in a failure long before this unit test is actually ran.
Help!
Looking at it now the problem seems relatively simple. PHP is running under the _www user and phpunit is running as the user that installed it. These users have different permissions, which makes perfect sense. If you somehow are encountering this problem I suggest you look at edorian's answer and re-evaluate how you are writing your unit tests.
First off:
For unit testing there is SplTempFileObject extends SplFileObject.
You usually don't need to create real files on the disk for that as it's slow anyways ;)
For an isReadable / isWriteable check in your phpunit tests you generally create ether create non readable / writeable files on the disk or use vfsStreamWrapper where applicable. It also works with SplFileObject.
Our issue:
In the test the last line should be removed. You except the exception during construct so let's make away with that ;)
What I found strange is that you have an absolute path there. Does your root folder structure really start with '/Library/WebServer/Documents/ ? Mainly I'm confused because that would imply that your tests are in a "WebServer" directory. Anyways.. moving on:
"Works for me"
Attached is a standalone version of the test that works and throws the exception like expected.
Apart from telling you that the problem seem to be somewhere else in your setup I don't see much I can do here. Maybe try the InvalidArgumentException without the / or try the test in isolation / with a newly created file.
PHPUnit doesn't interfere with the file handling functions so I'm out of idea apart from that. Does the sample code below work for you? :)
phpunit mep.php
PHPUnit 3.6.5 by Sebastian Bergmann.
.
Time: 1 second, Memory: 5.00Mb
OK (1 test, 1 assertion)
<?php
class FileLoggerTest extends PHPUnit_Framework_TestCase {
/**
* #expectedException InvalidArgumentException
*/
public function testReadOnlyFileObjectFailure() {
$file = __DIR__."/_files/test-log.txt";
touch($file);
chmod($file, 0444);
$LogFile = new \SplFileObject($file);
$Logger = new FileLogger($LogFile);
}
}
class FileLogger {
protected $LogFile;
public function __construct(SplFileObject $LogFile) {
$this->LogFile = $LogFile;
$this->throwExceptionIfFileNotWritable();
}
/**
* #throws InvalidArgumentException
*/
protected function throwExceptionIfFileNotWritable() {
$isWritable = $this->LogFile->isWritable();
if (!$isWritable) {
throw new InvalidArgumentException('The passed file, ' . $this->LogFile->getPathname() . ', is not writable.');
}
}
/**
* #param $timestamp A formatted timestamp string
* #param $message The message string to log
* #return boolean true if the message was logged, false if it wasn't
*/
public function log($timestamp, $message) {
if (!isset($timestamp) || empty($timestamp)) {
$timestamp = 'No timestamp given';
}
if (!isset($message) || empty($message)) {
$message = 'Attempting to log an empty message';
}
$separator = ' := ';
$message = $timestamp . $separator . $message;
$wasWritten = $this->LogFile->fwrite($message);
if (!isset($wasWritten)) {
return false;
}
return true;
}
}

How can I write to the console in PHP?

Is it possible write a string or log into the console?
What I mean
Just like in JSP, if we print something like system.out.println("some"), it will be there at the console, not at a page.
Or you use the trick from PHP Debug to console.
First you need a little PHP helper function
function debug_to_console($data) {
$output = $data;
if (is_array($output))
$output = implode(',', $output);
echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}
Then you can use it like this:
debug_to_console("Test");
This will create an output like this:
Debug Objects: Test
Firefox
On Firefox you can use an extension called FirePHP which enables the logging and dumping of information from your PHP applications to the console. This is an addon to the awesome web development extension Firebug.
http://www.studytrails.com/blog/using-firephp-in-firefox-to-debug-php/
Chrome
However if you are using Chrome there is a PHP debugging tool called Chrome Logger or webug (webug has problems with the order of logs).
More recently Clockwork is in active development which extends the Developer Tools by adding a new panel to provide useful debugging and profiling information. It provides out of the box support for Laravel 4 and Slim 2 and support can be added via its extensible API.
Using Xdebug
A better way to debug your PHP would be via Xdebug. Most browsers provide helper extensions to help you pass the required cookie/query string to initialize the debugging process.
Chrome - Xdebug Helper
Firefox - The easiest Xdebug
Opera - Xdebug
Safari - Xdebug Toggler
If you're looking for a simple approach, echo as JSON:
<script>
console.log(<?= json_encode($foo); ?>);
</script>
By default, all output goes to stdout, which is the HTTP response or the console, depending on whether your script is run by Apache or manually on the command line. But you can use error_log for logging and various I/O streams can be written to with fwrite.
Try the following. It is working:
echo("<script>console.log('PHP: " . $data . "');</script>");
As the author of the linked webpage in the popular answer, I would like to add my last version of this simple helper function. It is much more solid.
I use json_encode() to check if the variable type is unnecessary and add a buffer to solve problems with frameworks. There not have a solid return or excessive usage of header().
/**
* Simple helper to debug to the console
*
* #param $data object, array, string $data
* #param $context string Optional a description.
*
* #return string
*/
function debug_to_console($data, $context = 'Debug in Console') {
// Buffering to solve problems frameworks, like header() in this and not a solid return.
ob_start();
$output = 'console.info(\'' . $context . ':\');';
$output .= 'console.log(' . json_encode($data) . ');';
$output = sprintf('<script>%s</script>', $output);
echo $output;
}
Usage
// $data is the example variable, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console($data);`
Screenshot of the result
Also, a simple example as an image to understand it much easier:
$variable = "Variable";
echo "<script>console.log('$variable');</script>";
PHP and JavaScript interaction.
echo
"<div display='none'>
<script type='text/javascript'>
console.log('console log message');
</script>
</div>";
Creates a
<div>
with the
display="none"
so that the div is not displayed, but the
console.log()
function is created in javascript. So you get the message in the console.
I think it can be used --
function jsLogs($data, $isExit) {
$html = "";
$coll;
if (is_array($data) || is_object($data)) {
$coll = json_encode($data);
} else {
$coll = $data;
}
$html = "<script id='jsLogs'>console.log('PHP: ${coll}');</script>";
echo($html);
if ($isExit) exit();
}
# For String
jsLogs("Testing string"); #PHP: Testing string
# For Array
jsLogs(array("test1", "test2")); # PHP: ["test1","test2"]
# For Object
jsLogs(array("test1"=>array("subtest1", "subtest2"))); #PHP: {"test1":["subtest1","subtest2"]}
Some great answers that add more depth; but I needed something simpler and more like the JavaScript console.log() command.
I use PHP in a lot of "gathering data and turn into XML" in Ajax applications. The JavaScript console.log doesn't work in that case; it breaks the XML output.
Xdebug, etc. had similar issues.
My solution in Windows:
Setup a .txt file that is somewhat easily to get to and writable
Set the PHP error_log variable in the .ini file to write to that file
Open the file in Windows File Explorer and open a preview pane for it
Use the error_log('myTest'); PHP command to send messages
This solution is simple and meets my needs most of the time. Standard PHP, and the preview pane automatically updates every time PHP writes to it.
I find this helpful:
function console($data, $priority, $debug)
{
if ($priority <= $debug)
{
$output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';
echo $output;
}
}
And use it like:
<?php
$debug = 5; // All lower and equal priority logs will be displayed
console('Important', 1 , $debug);
console('Less Important', 2 , $debug);
console('Even Less Important', 5 , $debug);
console('Again Important', 1 , $debug);
?>
Which outputs in console:
Important
Less Important
Even Less Important
Again Important
And you can switch off less important logs by limiting them using the $debug value.
Short and easy, for arrays, strings or also objects.
function console_log( $data ) {
$output = "<script>console.log( 'PHP debugger: ";
$output .= json_encode(print_r($data, true));
$output .= "' );</script>";
echo $output;
}
For Chrome there is an extension called Chrome Logger allowing to log PHP messages.
The Firefox DevTools even have integrated support for the Chrome Logger protocol.
To enable the logging, you just need to save the 'ChromePhp.php' file in your project. Then it can be used like this:
include 'ChromePhp.php';
ChromePhp::log('Hello console!');
ChromePhp::log($_SERVER);
ChromePhp::warn('something went wrong!');
Example taken from the GitHub page.
The output may then look like this:
function phpconsole($label='var', $x) {
?>
<script type="text/javascript">
console.log('<?php echo ($label)?>');
console.log('<?php echo json_encode($x)?>');
</script>
<?php
}
If you want write to the PHP log file, and not the JavaScript console you can use this:
error_log("This is logged only to the PHP log")
Reference: error_log
I think best solution is to use
error_log(content)
This is output
Edit 2022:
So I’ve discovered way better way and thats file_put_contents("php://stdout", content)
It writes without the logging info
There is also a great Google Chrome extension, PHP Console, with a PHP library that allows you to:
See errors and exceptions in the Chrome JavaScript console and in the notification popups.
Dump any type of variable.
Execute PHP code remotely.
Protect access by password.
Group console logs by request.
Jump to error file:line in your text editor.
Copy error/debug data to the clipboard (for testers).
Here is my solution, the good thing about this one is that you can pass as many params as you like.
function console_log()
{
$js_code = 'console.log(' . json_encode(func_get_args(), JSON_HEX_TAG) .
');';
$js_code = '<script>' . $js_code . '</script>';
echo $js_code;
}
Call it this way
console_log('DEBUG>>', 'Param 1', 'Param 2');
console_log('Console DEBUG:', $someRealVar1, $someVar, $someArray, $someObj);
Now you should be able to see output in your console, happy coding :)
Any of these two are working:
<?php
$five = 5;
$six = 6;
?>
<script>
console.log(<?php echo $five + $six ?>);
</script>
<?php
$five = 5;
$six = 6;
echo("<script>console.log($five + $six);</script>");
?>
I was looking for a way to debug code in a WordPress plugin that I was developing and came across this post.
I took the bits of code that are most applicable to me from other responses and combined these into a function that I can use for debugging WordPress. The function is:
function debug_log($object=null, $label=null, $priority=1) {
$priority = $priority<1? 1: $priority;
$message = json_encode($object, JSON_PRETTY_PRINT);
$label = "Debug" . ($label ? " ($label): " : ': ');
echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}
Usage is as follows:
$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);
If this function is used with WordPress development, the function should be placed in the functions.php file of the child theme and can then be called anywhere in the code.
Clean, fast and simple without useless code:
function consolelog($data) {
echo "<script>console.log('".$data."');</script>";
}
Short and simply with printf and json_encode:
function console_log($data) {
printf('<script>console.log(%s);</script>', json_encode($data));
}
I have abandoned all of the above in favour of Debugger & Logger. I cannot praise it enough!
Just click on one of the tabs at top right, or on the "click here" to expand/hide.
Notice the different "categories". You can click any array to expand/collapse it.
From the web page
Main features:
Show globals variables ($GLOBALS, $_POST, $_GET, $_COOKIE, etc.)
Show PHP version and loaded extensions
Replace PHP built in error handler
Log SQL queries
Monitor code and SQL queries execution time
Inspect variables for changes
Function calls tracing
Code coverage analysis to check which lines of script where executed
Dump of all types of variable
File inspector with code highlighter to view source code
Send messages to JavaScript console (Chrome only), for Ajax scripts
As of 2017, Firebug and hence FirePHP has been disabled.
I wrote some little modifications to the ChromePHP tool to allow seamless migration from FirePHP to Firebug for debugging via the console.
This article explains in clear easy steps
Migrate from FirePHP to ChromePHP in 5 minutes (without breaking existing code)
For Ajax calls or XML / JSON responses, where you don't want to mess with the body, you need to send logs via HTTP headers, then add them to the console with a web extension. This is how FirePHP (no longer available) and QuantumPHP (a fork of ChromePHP) do it in Firefox.
If you have the patience, x-debug is a better option - you get deeper insight into PHP, with the ability to pause your script, see what is going on, then resume the script.
I might be late for a party, but I was looking for an implementation of logging function which:
takes a variable number of comma separated arguments, just like javascript console.log(),
gives a formatted output (not just a serialized string),
is distinguishable from a common javascript console.log().
So the output looks like that:
(The snippet below is tested on php 7.2.11. I'm not sure about its php backward compatibility. It can be an issue for javascript as well (in a term of old browsers), because it creates a trailing comma after console.log() arguments – which is not legal until ES 2017.)
<?php
function console_log(...$args)
{
$args_as_json = array_map(function ($item) {
return json_encode($item);
}, $args);
$js_code = "<script>console.log('%c 💬 log from PHP: ','background: #474A8A; color: #B0B3D6; line-height: 2',";
foreach ($args_as_json as $arg) {
$js_code .= "{$arg},";
}
$js_code .= ")</script>";
echo $js_code;
}
$list = ['foo', 'bar'];
$obj = new stdClass();
$obj->first_name = 'John';
$obj->last_name = 'Johnson';
echo console_log($list, 'Hello World', 123, $obj);
?>
Here's a handy function. It is super simple to use, allows you to pass as many arguments as you like, of any type, and will display the object contents in the browser console window as though you called console.log from JavaScript - but from PHP
Note, you can use tags as well by passing 'TAG-YourTag', and it will be applied until another tag is read, for example, 'TAG-YourNextTag'
/*
* Brief: Print to console.log() from PHP
*
* Description: Print as many strings,arrays, objects, and
* other data types to console.log from PHP.
*
* To use, just call consoleLog($data1, $data2, ... $dataN)
* and each dataI will be sent to console.log - note
* that you can pass as many data as you want an
* this will still work.
*
* This is very powerful as it shows the entire
* contents of objects and arrays that can be
* read inside of the browser console log.
*
* A tag can be set by passing a string that has the
* prefix TAG- as one of the arguments. Everytime a
* string with the TAG- prefix is detected, the tag
* is updated. This allows you to pass a tag that is
* applied to all data until it reaches another tag,
* which can then be applied to all data after it.
*
* Example:
*
* consoleLog('TAG-FirstTag', $data, $data2, 'TAG-SecTag, $data3);
*
* Result:
* FirstTag '...data...'
* FirstTag '...data2...'
* SecTag '...data3...'
*/
function consoleLog(){
if(func_num_args() == 0){
return;
}
$tag = '';
for ($i = 0; $i < func_num_args(); $i++) {
$arg = func_get_arg($i);
if(!empty($arg)){
if(is_string($arg) && strtolower(substr($arg, 0, 4)) === 'tag-'){
$tag = substr($arg, 4);
}else{
$arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
echo "<script>console.log('" . $tag . " " . $arg . "');</script>";
}
}
}
}
NOTE: func_num_args() and func_num_args() are PHP functions for reading a dynamic number of input arguments, and allow this function to have infinitely many console.log requests from one function call.
Though this is an old question, I've been looking for this. Here's my compilation of some solutions answered here and some other ideas found elsewhere to get a one-size-fits-all solution.
CODE :
// Post to browser console
function console($data, $is_error = false, $file = false, $ln = false) {
if(!function_exists('console_wer')) {
function console_wer($data, $is_error = false, $bctr, $file, $ln) {
echo '<div display="none">'.'<script type="text/javascript">'.(($is_error!==false) ? 'if(typeof phperr_to_cns === \'undefined\') { var phperr_to_cns = 1; document.addEventListener("DOMContentLoaded", function() { setTimeout(function(){ alert("Alert. see console."); }, 4000); }); }' : '').' console.group("PHP '.(($is_error) ? 'error' : 'log').' from "+window.atob("'.base64_encode((($file===false) ? $bctr['file'] : $file)).'")'.((($ln!==false && $file!==false) || $bctr!==false) ? '+" on line '.(($ln===false) ? $bctr['line'] : $ln).' :"' : '+" :"').'); console.'.(($is_error) ? 'error' : 'log').'('.((is_array($data)) ? 'JSON.parse(window.atob("'.base64_encode(json_encode($data)).'"))' : '"'.$data.'"').'); console.groupEnd();</script></div>'; return true;
}
}
return #console_wer($data, $is_error, (($file===false && $ln===false) ? array_shift(debug_backtrace()) : false), $file, $ln);
}
//PHP Exceptions handler
function exceptions_to_console($svr, $str, $file, $ln) {
if(!function_exists('severity_tag')) {
function severity_tag($svr) {
$names = [];
$consts = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true));
foreach ($consts as $code => $name) {
if ($svr & $code) $names []= $name;
}
return join(' | ', $names);
}
}
if (error_reporting() == 0) {
return false;
}
if(error_reporting() & $svr) {
console(severity_tag($svr).' : '.$str, true, $file, $ln);
}
}
// Divert php error traffic
error_reporting(E_ALL);
ini_set("display_errors", "1");
set_error_handler('exceptions_to_console');
TESTS & USAGE :
Usage is simple. Include first function for posting to console manually. Use second function for diverting php exception handling. Following test should give an idea.
// Test 1 - Auto - Handle php error and report error with severity info
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (Exception $e) {
echo "jsdlkjflsjfkjl";
}
// Test 2 - Manual - Without explicitly providing file name and line no.
console(array(1 => "Hi", array("hellow")), false);
// Test 3 - Manual - Explicitly providing file name and line no.
console(array(1 => "Error", array($some_result)), true, 'my file', 2);
// Test 4 - Manual - Explicitly providing file name only.
console(array(1 => "Error", array($some_result)), true, 'my file');
EXPLANATION :
The function console($data, $is_error, $file, $fn) takes string or array as first argument and posts it on console using js inserts.
Second argument is a flag to differentiate normal logs against errors. For errors, we're adding event listeners to inform us through alerts if any errors were thrown, also highlighting in console. This flag is defaulted to false.
Third and fourth arguments are explicit declarations of file and line numbers, which is optional. If absent, they're defaulted to using the predefined php function debug_backtrace() to fetch them for us.
Next function exceptions_to_console($svr, $str, $file, $ln) has four arguments in the order called by php default exception handler. Here, the first argument is severity, which we further crosscheck with predefined constants using function severity_tag($code) to provide more info on error.
NOTICE :
Above code uses JS functions and methods that are not available in older browsers. For compatibility with older versions, it needs replacements.
Above code is for testing environments, where you alone have access to the site. Do not use this in live (production) websites.
SUGGESTIONS :
First function console() threw some notices, so I've wrapped them within another function and called it using error control operator '#'. This can be avoided if you didn't mind the notices.
Last but not least, alerts popping up can be annoying while coding. For this I'm using this beep (found in solution : https://stackoverflow.com/a/23395136/6060602) instead of popup alerts. It's pretty cool and possibilities are endless, you can play your favorite tunes and make coding less stressful.
Use:
function console_log($data) {
$bt = debug_backtrace();
$caller = array_shift($bt);
if (is_array($data))
$dataPart = implode(',', $data);
else
$dataPart = $data;
$toSplit = $caller['file'])) . ':' .
$caller['line'] . ' => ' . $dataPart
error_log(end(split('/', $toSplit));
}
in start code...
error_reporting(-1);
ini_set('display_errors', 'On');
it work

How do I write unit tests in PHP? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've read everywhere about how great they are, but for some reason I can't seem to figure out how exactly I'm supposed to test something. Could someone perhaps post a piece of example code and how they would test it? If it's not too much trouble :)
There is a 3rd "framework", which is by far easier to learn - even easier than SimpleTest, it's called phpt.
A primer can be found here:
http://qa.php.net/write-test.php
Edit: Just saw your request for sample code.
Let's assume you have the following function in a file called lib.php:
<?php
function foo($bar)
{
return $bar;
}
?>
Really simple and straight forward, the parameter you pass in, is returned. So let's look at a test for this function, we'll call the test file foo.phpt:
--TEST--
foo() function - A basic test to see if it works. :)
--FILE--
<?php
include 'lib.php'; // might need to adjust path if not in the same dir
$bar = 'Hello World';
var_dump(foo($bar));
?>
--EXPECT--
string(11) "Hello World"
In a nutshell, we provide the parameter $bar with value "Hello World" and we var_dump() the response of the function call to foo().
To run this test, use: pear run-test path/to/foo.phpt
This requires a working install of PEAR on your system, which is pretty common in most circumstances. If you need to install it, I recommend to install the latest version available. In case you need help to set it up, feel free to ask (but provide OS, etc.).
There are two frameworks you can use for unit testing. Simpletest and PHPUnit, which I prefer. Read the tutorials on how to write and run tests on the homepage of PHPUnit. It is quite easy and well described.
You can make unit testing more effective by changing your coding style to accommodate it.
I recommend browsing the Google Testing Blog, in particular the post on Writing Testable Code.
I rolled my own because i didnt have time to learn someone elses way of doing things, this took about 20 minutes to write up, 10 to adapt it for posting here.
Unittesting is very usefull to me.
this is kinda long but it explains itself and there is an example at the bottom.
/**
* Provides Assertions
**/
class Assert
{
public static function AreEqual( $a, $b )
{
if ( $a != $b )
{
throw new Exception( 'Subjects are not equal.' );
}
}
}
/**
* Provides a loggable entity with information on a test and how it executed
**/
class TestResult
{
protected $_testableInstance = null;
protected $_isSuccess = false;
public function getSuccess()
{
return $this->_isSuccess;
}
protected $_output = '';
public function getOutput()
{
return $_output;
}
public function setOutput( $value )
{
$_output = $value;
}
protected $_test = null;
public function getTest()
{
return $this->_test;
}
public function getName()
{
return $this->_test->getName();
}
public function getComment()
{
return $this->ParseComment( $this->_test->getDocComment() );
}
private function ParseComment( $comment )
{
$lines = explode( "\n", $comment );
for( $i = 0; $i < count( $lines ); $i ++ )
{
$lines[$i] = trim( $lines[ $i ] );
}
return implode( "\n", $lines );
}
protected $_exception = null;
public function getException()
{
return $this->_exception;
}
static public function CreateFailure( Testable $object, ReflectionMethod $test, Exception $exception )
{
$result = new self();
$result->_isSuccess = false;
$result->testableInstance = $object;
$result->_test = $test;
$result->_exception = $exception;
return $result;
}
static public function CreateSuccess( Testable $object, ReflectionMethod $test )
{
$result = new self();
$result->_isSuccess = true;
$result->testableInstance = $object;
$result->_test = $test;
return $result;
}
}
/**
* Provides a base class to derive tests from
**/
abstract class Testable
{
protected $test_log = array();
/**
* Logs the result of a test. keeps track of results for later inspection, Overridable to log elsewhere.
**/
protected function Log( TestResult $result )
{
$this->test_log[] = $result;
printf( "Test: %s was a %s %s\n"
,$result->getName()
,$result->getSuccess() ? 'success' : 'failure'
,$result->getSuccess() ? '' : sprintf( "\n%s (lines:%d-%d; file:%s)"
,$result->getComment()
,$result->getTest()->getStartLine()
,$result->getTest()->getEndLine()
,$result->getTest()->getFileName()
)
);
}
final public function RunTests()
{
$class = new ReflectionClass( $this );
foreach( $class->GetMethods() as $method )
{
$methodname = $method->getName();
if ( strlen( $methodname ) > 4 && substr( $methodname, 0, 4 ) == 'Test' )
{
ob_start();
try
{
$this->$methodname();
$result = TestResult::CreateSuccess( $this, $method );
}
catch( Exception $ex )
{
$result = TestResult::CreateFailure( $this, $method, $ex );
}
$output = ob_get_clean();
$result->setOutput( $output );
$this->Log( $result );
}
}
}
}
/**
* a simple Test suite with two tests
**/
class MyTest extends Testable
{
/**
* This test is designed to fail
**/
public function TestOne()
{
Assert::AreEqual( 1, 2 );
}
/**
* This test is designed to succeed
**/
public function TestTwo()
{
Assert::AreEqual( 1, 1 );
}
}
// this is how to use it.
$test = new MyTest();
$test->RunTests();
This outputs:
Test: TestOne was a failure
/**
* This test is designed to fail
**/ (lines:149-152; file:/Users/kris/Desktop/Testable.php)
Test: TestTwo was a success
Get PHPUnit. It is very easy to use.
Then start with very simple assertions. You can do alot with AssertEquals before you get into anything else. That's a good way to get your feet wet.
You may also want to try writing your test first (since you gave your question the TDD tag) and then write your code. If you haven't done this before it is an eye-opener.
require_once 'ClassYouWantToTest';
require_once 'PHPUnit...blah,blah,whatever';
class ClassYouWantToTest extends PHPUnit...blah,blah,whatever
{
private $ClassYouWantToTest;
protected function setUp ()
{
parent::setUp();
$this->ClassYouWantToTest = new ClassYouWantToTest(/* parameters */);
}
protected function tearDown ()
{
$this->ClassYouWantToTest = null;
parent::tearDown();
}
public function __construct ()
{
// not really needed
}
/**
* Tests ClassYouWantToTest->methodFoo()
*/
public function testMethodFoo ()
{
$this->assertEquals(
$this->ClassYouWantToTest->methodFoo('putValueOfParamHere), 'expectedOutputHere);
/**
* Tests ClassYouWantToTest->methodBar()
*/
public function testMethodFoo ()
{
$this->assertEquals(
$this->ClassYouWantToTest->methodBar('putValueOfParamHere), 'expectedOutputHere);
}
For simple tests AND documentation, php-doctest is quite nice and it's a really easy way to get started since you don't have to open a separate file. Imagine the function below:
/**
* Sums 2 numbers
* <code>
* //doctest: add
* echo add(5,2);
* //expects:
* 7
* </code>
*/
function add($a,$b){
return $a + $b;
}
If you now run this file through phpdt (command-line runner of php-doctest) 1 test will be run. The doctest is contained inside the < code > block. Doctest originated in python and is fine for giving useful & runnable examples on how the code is supposed to work. You can't use it exclusively because the code itself would litter up with test cases but I've found that it's useful alongside a more formal tdd library - i use phpunit.
This 1st answer here sums it up nicely (it's not unit vs doctest ).
phpunit is pretty much the defacto unit testing framework for php. there is also DocTest (available as a PEAR package) and a few others.
php itself is tested for regressions and the like via phpt tests which can also be run via pear.
Codeception tests are much like common unit tests but are much powerful in things where you need mocking and stubbing.
Here is the sample controller test. Notice how easily stubs are created. How easily you check the method was invoked.
<?php
use Codeception\Util\Stub as Stub;
const VALID_USER_ID = 1;
const INVALID_USER_ID = 0;
class UserControllerCest {
public $class = 'UserController';
public function show(CodeGuy $I) {
// prepare environment
$I->haveFakeClass($controller = Stub::makeEmptyExcept($this->class, 'show'));
$I->haveFakeClass($db = Stub::make('DbConnector', array('find' => function($id) { return $id == VALID_USER_ID ? new User() : null ))); };
$I->setProperty($controller, 'db', $db);
$I->executeTestedMethodOn($controller, VALID_USER_ID)
->seeResultEquals(true)
->seeMethodInvoked($controller, 'render');
$I->expect('it will render 404 page for non existent user')
->executeTestedMethodOn($controller, INVALID_USER_ID)
->seeResultNotEquals(true)
->seeMethodInvoked($controller, 'render404','User not found')
->seeMethodNotInvoked($controller, 'render');
}
}
Also there are other cool things. You can test database state, filesystem, etc.
Besides the excellent suggestions about test frameworks already given, are you building your application with one of the PHP web frameworks that has automated testing built in, such as Symfony or CakePHP? Sometimes having a place to just drop in your test methods reduces the start-up friction some people associate with automated testing and TDD.
Way too much to re-post here, but here is a great article on using phpt. It covers a number of aspects around phpt that are often overlooked, so it could be worth a read to expand your knowledge of php beyond just writing a test. Fortunately the article also discusses writing tests!
The main points of discussion
Discover how marginally documented aspects of PHP work (or pretty much any part for that matter)
Write simple unit tests for your own PHP code
Write tests as part of an extension or to convey a potential bug to the internals or QA groups
I know there is a lot of info here already, but since this still shows up on Google searches i might as well add Chinook Test Suite to the list. It is a simple and small test framework.
You can easily test your classes with it and also create mock objects. You run the tests through a web browser and (not yet) through a console.
In the browser you can specify what test class or even what test method to run. Or you can simply run all tests.
A screenshot from the github page:
What i like about it is the way you assert tests. This is done with so called "fluent assertions". Example:
$this->Assert($datetime)->Should()->BeAfter($someDatetime);
And creating mock objects is a breeze too (with a fluent like syntax):
$mock = new CFMock::Create(new DummyClass());
$mock->ACallTo('SomeMethod')->Returns('some value');
Anyway, more info can be found on the github page with a code example as well:
https://github.com/w00/Chinook-TestSuite

Categories