PHPUnit mock一个对象实例及其代码!

jackxiang 2008-11-4 20:05 | |
文件:
         a.php  b.php  
         aTest.php

a.php:


<?php
class a
{
  private $inHandle;
    public function getHandle($handle='')
    {  
        if ('' != $handle)
        {  
            $this->inHandle = $handle;
            return ;
        }  
        elseif ('' != $this->inHandle)
        {  
            return;
        }  
        $this->inHandle = new b();
        return;
    }
  public function use_b_class($num)
  {  //调用b类的:need_mock方法,假如是外部资源,为此需要mock
    $value = $this->inHandle->need_mock($num);
    $result = $value;
    return $result;    
  }  
}
?>



b.php



<?php
class b
{  protected $a = 0;
  protected $b = 0;
  public function __construct($a,$b)
  {
    $this->a = $a;
    $this->b = $b;
    echo $this->b;    
  }
  public function  need_mock($a)
  {
    $b = $this->a+$a;
    return $b;
  }
}
?>


aTest.php

<?php
require_once 'a.php';
require_once 'b.php';
require_once 'PHPUnit/Framework/TestCase.php';
/**
* a test case.
*/
class aTest extends PHPUnit_Framework_TestCase {  
  /**
   * @var a
   */
  private $a;  
  /**
   * Prepares the environment before running a test.
   */
  protected function setUp() {
    parent::setUp ();    
    // TODO Auto-generated aTest::setUp()
    $this->a = new a(/* parameters */);
  }  
  /**
   * Cleans up the environment after running a test.
   */
  protected function tearDown() {
    // TODO Auto-generated aTest::tearDown()
    $this->a = null;    
    parent::tearDown ();
  }
  
  /**
   * Constructs the test case.
   */
  public function __construct() {
    // TODO Auto-generated constructor
  }
  
  /**
   * Tests a->getHandle()
   */
  public function testGetHandle() {
    // TODO Auto-generated aTest->testGetHandle()
    $this->markTestIncomplete ( "getHandle test not implemented" );    
    $this->a->getHandle(/* parameters */);  
  }
  
  /**
   * Tests a->use_b_class()
   */
  public function testUse_b_class() {
    // TODO Auto-generated aTest->testUse_b_class()
    //$this->markTestIncomplete ( "use_b_class test not implemented" );
    
    //$this->a->use_b_class(/* parameters */);
    $a = array(1,"第二个参数");//注意:必须传array(构造函数参数1,构造函数参数2,构造函数参数3)
    $stub = $this->getMock('b', array('need_mock'),$a);
        $stub->expects($this->any())
             ->method('need_mock')
             ->with(      
                   $this->equalTo( 1 )//传入一个参数
                   )
             ->will($this->returnValue(11));//设定返回为11
        $this->a->getHandle($stub);//传入经过mock的对象      
        echo $this->a->use_b_class(1);
        $this->assertEquals($this->a->use_b_class(1) , 11 );
        $this->assertEquals(array(array(0,1,2)),array(array(0,1,2)));//必须是所谓的二维数组,否则出错
  
  }

}



作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/1354/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!

评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]