How to create unit test for the function “beforeControllerAction” extended from yii framework

百般思念 提交于 2019-12-12 02:57:16

问题


I need some idea, to create unit test for the action 'beforeControllerAction', which is extended from yii framework.


回答1:


beforeControllerAction is parent method from any 'mycontroller' app controller, coming from framework core. You don't need to test specific core framework code (is already tested). You need to test your own code.

One way to test your controller is to extend/inherit your own 'mycontroller' controller first and build a test for it. Taken from this excellent article:

Create your unit test class under the protected/tests/unit folder and name it the same as your class name you want to test, adding a Test word after it.

In my case, I will create a file named ApiControllerTest.php that contains all tests for ApiController.php class.

<?php

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

class ApiControllerTest extends ApiController 
{ 
}

Open your ApiControllerTest.php unit test class in step #1 above and make it something similar like this (based on your requirement and structure):

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

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

Let’s try to test one single method in my ApiController.php, that is formatResponseHeader. This is what it is doing.

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

Now, to test this method, I’ll open ApiControllerTest.php and add this code below after setUp() and before tearDown() methods:

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'));
}

Save the change in ApiControllerTest.php and then try to run this in protected/tests directory:

phpunit .


来源:https://stackoverflow.com/questions/31113969/how-to-create-unit-test-for-the-function-beforecontrolleraction-extended-from

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!