Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :)

like image 811
letgo Avatar asked Nov 11 '08 21:11

letgo


People also ask

How do you cover a test code?

To calculate the code coverage percentage, simply use the following formula: Code Coverage Percentage = (Number of lines of code executed by a testing algorithm/Total number of lines of code in a system component) * 100.

How do I run a test case in PHP?

From the Menu-bar, select Run | Run As | PHPUnit Test . To debug the PHPUnit Test Case, click the arrow next to the debug button on the toolbar, and select Debug As | PHPUnit Test . From the Main Menu, select Run | Debug As | PHPUnit Test . The unit test will be run and a PHP Unit view will open.

What is Codeception PHP?

Codeception is a framework used for creating tests, including unit tests, functional tests, and acceptance tests. Despite the fact that it is based on PHP, the user needs only basic knowledge for starting work with the framework, thanks to the set of custom commands offered by Codeception.


2 Answers

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.).

like image 149
Till Avatar answered Oct 03 '22 05:10

Till


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.

like image 31
okoman Avatar answered Oct 03 '22 04:10

okoman