【问题标题】:How to create unit test for the function "beforeControllerAction" extended from yii framework如何为从 yii 框架扩展的函数“beforeControllerAction”创建单元测试
【发布时间】:2015-09-15 19:34:10
【问题描述】:

我需要一些想法,为动作“beforeControllerAction”创建单元测试,它是从 yii 框架扩展而来的。

【问题讨论】:

  • 'beforeControllerAction' 是来自任何 'mycontroller' 应用控制器的父方法。您不需要测试特定的核心框架代码(已测试)。一种方法是首先扩展/继承您自己的“mycontroller”控制器并为其构建测试。在这里你有一篇很好的文章解释了这个和其他测试方法blog.ksetyadi.com/2013/10/…
  • 不错的链接@Alejandro。花点时间将详细信息(不仅仅是链接)作为答案,这样它将是一个独立的响应,即使链接页面消失,它仍然可用。
  • 谢谢@crafter,我会做的

标签: yii phpunit


【解决方案1】:

beforeControllerAction 是来自任何“mycontroller”应用控制器的父方法,来自框架核心。您不需要测试特定的核心框架代码(已测试)。您需要测试自己的代码。

测试您的控制器的一种方法是首先扩展/继承您自己的“mycontroller”控制器并为其构建测试。取自excellent article

在 protected/tests/unit 下创建你的单元测试类 文件夹并将其命名为与您要测试的类名相同, 在其后添加一个Test 字。

在我的例子中,我将创建一个名为 ApiControllerTest.php 的文件 包含 ApiController.php 类的所有测试。

<?php

// You can use Yii import or PHP require_once to refer your original file
Yii::import('application.controllers.ApiController');

class ApiControllerTest extends ApiController 
{ 
}

在第 1 步中打开您的 ApiControllerTest.php 单元测试类 上面并使其类似于这样(基于您的 要求和结构):

class ApiControllerTest extends CTestCase 
{ 
  public function setUp() 
  {
    $this->api = new ApiController(rand()); 
  } 

  public function tearDown() 
  {
    unset($this->api); 
  } 
}

让我们尝试在我的 ApiController.php 中测试一个方法,即 格式响应头。这就是它正在做的事情。

public function formatResponseHeader($code)
{ 
  if (!array_key_exists($code, $this->response_code)) 
  { 
    $code = '400'; 
  } 
  return 'HTTP/1.1 ' . $code . ' ' . $this->response_code[$code]; 
}

现在,为了测试这个方法,我将打开 ApiControllerTest.php 并添加这个 下面的代码在 setUp() 之后和 tearDown() 方法之前:

public function testFormatResponseHeader() 
{
  $this->assertEquals('HTTP/1.1 400 Bad Request',$this->api->formatResponseHeader('400'));
  $this->assertEquals('HTTP/1.1 200 OK',$this->api->formatResponseHeader('200'));
  $this->assertEquals('HTTP/1.1 400 Bad Request',$this->api->formatResponseHeader('500'));
  $this->assertNotEquals('HTTP/1.1 304 Not Modified',$this->api->formatResponseHeader('204'));
}

在 ApiControllerTest.php 中保存更改,然后尝试在其中运行它 protected/tests 目录:

phpunit .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-29
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2018-06-03
    相关资源
    最近更新 更多