makeweb / wordpress-test-environment

启动WordPress以在真实环境中测试您的代码

1.1.2 2018-07-13 09:07 UTC

This package is not auto-updated.

Last update: 2024-09-25 08:34:03 UTC


README

将WordPress轻松拉入您的插件、库或包中,作为composer开发依赖项,并在真实环境中测试您的代码。

此包旨在以两种主要方式支持希望测试依赖WordPress的代码的开发者

  1. 启动WordPress以允许使用WordPress数据库和全局函数

  2. 模拟对WordPress应用程序的实际HTTP请求

安装

从命令行

composer require --dev makeweb/wordpress-test-environment

基本用法

  1. 安装后,在您本地的MySQL安装中创建一个新的数据库。

  2. 在您要测试的代码库的根目录中创建一个.env文件,并将其添加以下内容(更新凭据以匹配您新创建的数据库和本地环境)

DATABASE_NAME=database_name_here
DATABASE_USER=database_user_here
DATABASE_PASSWORD=database_password_here
DATABASE_HOST=127.0.0.1
SITE_URL=example.test
  1. 在您的父测试用例类中初始化WordPress

将包含您的.env文件的目录的相对路径传递给loadEnvFrom()

use MakeWeb\WordpressTestEnvironment\Wordpress;
use PHPUnit\Framework\TestCase as BaseTestCase;

class TestCase extends BaseTestCase;
{
    public function setUp()
    {
        $this->wordpress = (new Wordpress)
            ->loadEnvFrom(__DIR__.'/..');
    } 
}
  1. 在测试中使用

仅启动

如果您只想启动WordPress以允许访问数据库和WordPress全局函数。请将以下行添加到测试的开头。

在您的测试文件中

class MyPluginTest extends TestCase
{
    public function the_main_plugin_class_can_use_wordpress_global_functions()
    {
        $this->wordpress->boot();

        $this->assertEquals('http://example.test', (new MyPluginClass)->url());
    }
}

在您的主插件文件或源代码中

这里我们只是调用一个原生的WordPress函数get_site_url()。如果一切设置正确,上面的测试将通过以下代码通过,因为get_site_url()已被WordPress定义。

注意:确保您手动或使用类似composer的自加载器将插件文件包含在测试引导文件中

class MyPluginClass
{
    public function url()
    {
        return get_site_url();
    }
}

测试对WordPress应用程序的HTTP请求

有时您的主题、插件或库可能实际上会处理HTTP请求(例如,如果您正在创建API),或者您可能只是想测试您的代码如何影响应用程序的实际HTML输出。WordPress类公开了一个get方法,该方法模拟对给定URL的实际HTTP GET请求。WordPress和您的依赖代码将启动并执行,就像在生产环境中一样。我们不需要在使用HTTP方法时调用$this->wordpress->boot(),因为它会自动为我们完成。

在您的测试文件中

class MyPluginTest extends TestCase
{
    public function the_main_plugin_class_can_use_wordpress_global_functions()
    {
        // To boot the plugin which we are testing when booting wordpress, pass the relative path
        // to the main plugin file into the withPlugin() method. Installation and activation hooks
        // will not be called.
        $this->wordpress->withPlugin(__DIR__.'/../edd-sl-deployer.php');

        // Request the front page of the wordpress site and capture the result
        $response = $this->wordpress->get('/');

        // Assert that the response returned a 200 http status code
        $response->assertSuccessful();

        // Assert that our text was output in the html
        $response->assertSee('Hello World');
    }
}

在您的插件文件或源代码中

/**
 * Plugin Name: Hello World Outputter
 * Plugin Description: An enterprise ready solution to output the text 'Hello World' on your website
 * Plugin URI: https://hello-world-outputter.com
 * Version: 1.0.0
 * Author: Andrew Feeney
**/

class MyPluginClass
{
    public function boot()
    {
        echo('Hello World');
    }
}

(new MyPluginClass)->boot();