[PHP] Configuring PHPUnit for ThinkPHP

Version Details

PHP: 5.3

PHPUnit

ThinkPHP 3.1.3

IDE: PHPStorm 10 (recommended)

Configuring PHPUnit in PHPStorm

See the blog post:

http://blog.coinidea.com/web开发/php-1088.html

ThinkPHP Deployment

Official code download:

http://www.thinkphp.cn/down.html

Site initialization:

http://www.thinkphp.cn/info/60.html

Test Cases

In this example, the index.php in the root directory is configured as follows:

1
2
3
4
5
6
7
<?php
define('APP_NAME', 'example');
define('APP_PATH', '../example/');
define('APP_PHPUNIT', false);
define('APP_DEBUG', true);
require('../ThinkPHP/ThinkPHP.php');
?>

After the first visit, the following directory structure is generated:

image001

Create a new folder named “Testcase” in the example site.

Testing the Model

Create HelloModel.class.php:

1
2
3
4
5
6
7
8
9
<?php
class HelloModel extends Model
{
    public function sayHello()
    {
        print 'Hello';
        return 'Hello';
    }
}

Create a Test.php file in the Test folder as the PHPUnit test file. Note that you need to require ThinkPHP to initialize the framework environment. Also, in Think.class.php, modify the

start() function by changing App::run() to !APP_PHPUNIT && App::run();

This distinguishes between site runtime and test case execution.

image003

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php
define('APP_NAME', 'example');
define('APP_PATH', './../../example/');
define('APP_PHPUNIT', true);
require('./../../ThinkPHP/ThinkPHP.php');
class TestSayHello extends PHPUnit_Framework_TestCase {

public function setUp() { }

public function tearDown(){ }

}

Add a test case in TestSayHello:

1
2
3
4
5
public function testHelloModel()
{
    $hello = D('Hello');
    $this->assertTrue($hello->sayHello('Hello') == 'Hello');
}

Testing the Action

Modify IndexAction.class.php as follows:

1
2
3
4
5
6
7
8
9
<?php
class IndexAction extends Action
{
    public function index()
    {
        $hello = D("Hello");
        return $hello->sayHello();
    }
}

Browser access to Index:

image005

Add a test case in TestSayHello:

1
2
3
4
5
public function testHelloAction()
{
    $hello = new IndexAction();
    $this->assertTrue($hello->index() == 'Hello');
}

Results

Running Test.php produces the following result:

image007

Tests passed. At this point, unit testing has been successfully added to ThinkPHP.


poisonbian 2016/05/10 14:57

I tried following this guide and found that the model couldn’t be used, and custom functions in the Common directory were not loaded. After some investigation, I think adding the APP_PHPUNIT check in Think.class.php is not ideal. It would be better to add it in App.class.php instead: !APP_PHPUNIT && App::exec();