Yii2测试环境扩展开发指南

时间:2015-10-31 18:24:50

标签: php testing yii2 integration

我正在开发一个Yii 2公共(MIT)扩展来改变一些yii\web\View行为(缩小,组合和许多其他优化)。

我可以轻松地做到。但我真的想为它编写尽可能多的测试(代码)。这是我非常困惑的地方。

我已经有一些单元测试(例如:测试特定的minifing,或返回组合缩小的结果)。但我想测试整个结果以及我的扩展和使用它的Yii2 Web应用程序之间的最终集成。

我只想了解这个过程的一些指导原则:

  1. 我的扩展程序中是否应该有一个真实的(完整的)应用程序用于测试目的?如果是这样,是否应该安装'内部测试dir?

  2. 您会使用功能测试吗? (我认为是因为View会在AssetBundles找到文件,合并缩小它们,发布结果作为单个文件,并在视图内用新网址(即优化资产网址)替换资产网址;

  3. 您能否提供一些非常基本的示例/指南?

  4. 我只想突出显示,我不打算你做我的测试工作,我真的想学习如何做到这一点。这就是为什么我真的非常感谢任何提示。

    非常感谢你。

2 个答案:

答案 0 :(得分:4)

我自己的指南

好的,我找到了基于yii2-smarty内部测试的方法。

因此,这些是使用phpunit测试您自己的Yii2扩展开发的指南:

1)tests / bootstrap.php:

// ensure we get report on all possible php errors
error_reporting(-1);

define('YII_ENABLE_ERROR_HANDLER', false);
define('YII_DEBUG', true);

$_SERVER['SCRIPT_NAME'] = '/' . __DIR__;
$_SERVER['SCRIPT_FILENAME'] = __FILE__;

require_once(__DIR__ . '/../vendor/autoload.php');
require_once(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

//optionals
Yii::setAlias('@testsBasePathOrWhateverYouWant', __DIR__);
Yii::setAlias('@slinstj/MyExtensionAlias', dirname(__DIR__));

2)创建扩展\PHPUnit_Framework_TestCase

的tests / TestCase基类
namespace slinstj\MyExtension\tests;

use yii\di\Container;

/**
 * This is the base class for all yii framework unit tests.
 */
abstract class TestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * Clean up after test.
     * By default the application created with [[mockApplication]] will be destroyed.
     */
    protected function tearDown()
    {
        parent::tearDown();
        $this->destroyApplication();
    }

    /**
     * Populates Yii::$app with a new application
     * The application will be destroyed on tearDown() automatically.
     * @param array $config The application configuration, if needed
     * @param string $appClass name of the application class to create
     */
    protected function mockApplication($config = [], $appClass = '\yii\console\Application')
    {
        new $appClass(ArrayHelper::merge([
            'id' => 'testapp',
            'basePath' => __DIR__,
            'vendorPath' => dirname(__DIR__) . '/vendor',
        ], $config));
    }

    protected function mockWebApplication($config = [], $appClass = '\yii\web\Application')
    {
        new $appClass(ArrayHelper::merge([
            'id' => 'testapp',
            'basePath' => __DIR__,
            'vendorPath' => dirname(__DIR__) . '/vendor',
            'components' => [
                'request' => [
                    'cookieValidationKey' => 'wefJDF8sfdsfSDefwqdxj9oq',
                    'scriptFile' => __DIR__ .'/index.php',
                    'scriptUrl' => '/index.php',
                ],
            ]
        ], $config));
    }

    /**
     * Destroys application in Yii::$app by setting it to null.
     */
    protected function destroyApplication()
    {
        Yii::$app = null;
        Yii::$container = new Container();
    }

    protected function debug($data)
    {
        return fwrite(STDERR, print_r($data, TRUE));
    }
}

3)创建扩展TestCase

的testSomething类
namespace slinstj\MyExtension\tests;

use yii\web\AssetManager;
use slinstj\MyExtension\View;
use Yii;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2015-10-30 at 17:45:03.
 */
class ViewTest extends TestCase
{

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        parent::setUp();
        $this->mockWebApplication();
    }

    public function testSomething()
    {
        $view = $this->mockView();
        $content = $view->renderFile('@someAlias/views/index.php', ['data' => 'Hello World!']);

        $this->assertEquals(1, preg_match('#something#', $content), 'Html view does not contain "something": ' . $content);
    }

    //other tests...

    /**
     * @return View
     */
    protected function mockView()
    {
        return new View([
            'someConfig' => 'someValue',
            'assetManager' => $this->mockAssetManager(),
        ]);
    }

    protected function mockAssetManager()
    {
        $assetDir = Yii::getAlias('@the/path/to/assets');
        if (!is_dir($assetDir)) {
            mkdir($assetDir, 0777, true);
        }

        return new AssetManager([
            'basePath' => $assetDir,
            'baseUrl' => '/assets',
        ]);
    }

    protected function findByRegex($regex, $content, $match = 1)
    {
        $matches = [];
        preg_match($regex, $content, $matches);
        return $matches[$match];
    }
}

就是这样!此代码框架高度基于yii2-smaty / tests代码。希望能帮助你(以及我的进一步需求)。

答案 1 :(得分:0)

这种方法有效,但我不得不做一些小的调整:

  1. 如果您正在开发扩展(在/ vendor / / 扩展名目录中)并且bootstrap.php文件位于test-directory中,自动加载器和yii基类的路径很可能是错误的。更好的是:

    private bool UserLogin(string un, string pw)
    {
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("Select username from CTM_DATABASE.dbo.users where username=@un and password=@pw", con);
        cmd.Parameters.AddWithValue("@un", un);
        cmd.Parameters.AddWithValue("@pw", pw);
        con.Open();
    
        string result = Convert.ToString(cmd.ExecuteScalarAsync());
        if(String.IsNullOrEmpty(result))  return false; return true;
    }
    
  2. 我测试了一个需要应用程序对象的验证器类。我只是在bootstrap文件中创建了一个控制台应用程序(追加到文件末尾):

    require_once(__DIR__ . '/../../../autoload.php');
    require_once(__DIR__ . '/../../../yiisoft/yii2/Yii.php');
    
相关问题