如何为函数创建单元测试;“控制措施之前”;从yii框架扩展

如何为函数创建单元测试;“控制措施之前”;从yii框架扩展,yii,phpunit,Yii,Phpunit,我需要一些想法,为操作“beforeControllerAction”创建单元测试,它是从yii框架扩展而来的。beforeControllerAction是来自框架核心的任何“mycontroller”应用程序控制器的父方法。您不需要测试特定的核心框架代码(已经过测试)。您需要测试自己的代码 测试控制器的一种方法是首先扩展/继承您自己的“mycontroller”控制器,并为其构建测试。摘自: 在protected/tests/unit下创建单元测试类 文件夹,并将其命名为要测试的类名, 在后

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

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

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

在protected/tests/unit下创建单元测试类 文件夹,并将其命名为要测试的类名, 在后面添加一个
测试
单词

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

让我们尝试在我的ApiController.php中测试一个方法,即 formatResponseHeader。这就是它正在做的

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

将更改保存在ApiControllerTest.php中,然后尝试在中运行 受保护/测试目录:


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

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

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

  public function tearDown() 
  {
    unset($this->api); 
  } 
}
public function formatResponseHeader($code)
{ 
  if (!array_key_exists($code, $this->response_code)) 
  { 
    $code = '400'; 
  } 
  return 'HTTP/1.1 ' . $code . ' ' . $this->response_code[$code]; 
}
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'));
}
phpunit .