Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

phpunit - How to create unit test for the function "beforeControllerAction" extended from yii framework

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 .

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...