2012-05-13 4 views
3

phpunit과 단위 테스트를 처음 접해 보았습니다. 대형 응용 프로그램을 cakephp 2.0으로 변환하고 모든 것을 단위 테스트 해보려고합니다.CakePHP 2.1 : Session :: read()를 사용하여 모의 컨트롤러 만들기

$ this-> Session-> read ('Auth.Account.id')가 호출 될 때 mock 객체를 만들려고합니다.이 객체는 144를 반환합니다 ... 이것은 id가있는 계정을 제공합니다. 그 항목이 있습니다.

그러나 모의는 다양한 BeforeFilter 호출에서 다른 Session :: read ('AuthCode') 호출에서 오류가 발생하는 것처럼 보입니다.

기대는 메소드 이름에 실패하면 기대 값과 일치하지 않는 1 시간 (들)을 호출 SessionComponent에 대한 매개 변수 0 :: ('AUTHCODE') 읽기를 호출 할 때와 동일합니다. 두 개의 문자열이 같다고 주장하지 못했습니다.

내가 말했듯이 phpunit 및 단위 테스트가 처음이라 ... 내가 뭘 잘못하고있는 걸까요?

class PagesController extends MastersController { 
     public function support(){ 
     if($this->Session->read('Auth.Account.id')) { 
      $items = $this->Account->Items->find('list', array('conditions'=>array('Items.account_id'=>$this->Session->read('Auth.Account.id'))));   
     } 
     $this->set(compact('items')); 
    } 
} 


class PagesControllerTestCase extends CakeTestCase { 
     /** 
    * Test Support 
    * 
    * @return void 
    */ 
    public function testSupport() { 
     #mock controller 
     $this->PagesController = $this->generate('Pages', array(
      'methods'=>array('support'), 
      'components' => array(
       'Auth', 
       'Session', 
      ), 
     )); 

       #mock controller expects 
     $this->PagesController->Session->expects(
      $this->once()) 
       ->method('read') #Session:read() method will be called at least once 
       ->with($this->equalTo('Auth.Account.id')) #when read method is called with 'Auth.Account.id' as a param 
       ->will($this->returnValue(144)); #will return value 144 


     #test action 
     $this->testAction('support'); 
    } 
} 
+0

을 내가 적어도 올바르게 생각 해요입니다 ... $ this-> PagesController- > 세션 -> ('this Auth.Account.id') -> will ($ this-> onceVal) (144)); Session :: read ('Auth.Account.id')가 한 번만 호출 될 때 144를 반환한다고 가정합니까? beforeFilter 호출에서 Session :: read ('AuthCode')가 실행되면 발사되지 않습니다. 맞습니까? 내가 phpunit과 unit testing을 처음 접했을 때 말했듯이, 이렇게 할 수 있다고 생각하니? – devnull

답변

1

당신은 인증 구성 요소가 아닌 세션 구성 요소 인증 세션 변수에 액세스해야합니다. 대신

if($this->Session->read('Auth.Account.id')) {

은 동일

if ($this->Auth->user('Account.id')) {

이 항목에 간다 시도 :: 전화를 찾을 수 있습니다.

인증 구성 요소를 조롱하는 것은 여전히 ​​방법입니다.

class PagesControllerTestCase extends CakeTestCase {

테스트에서

class PagesControllerTestCase extends ControllerTestCase {

다음과 같아야합니다

$PagesController = $this->generate('Pages', array(
    'methods'=>array('support'), 
    'components' => array(
     'Auth' => array('user') 
    ), 
)); 

$PagesController->Auth->staticExpects($this->exactly(2)) 
    ->method('user') 
    ->with('Account.id') 
    ->will($this->returnValue(144));