2014-01-20 134 views
2

我正在使用PHPUnit来单元测试我的应用程序(使用Zend Framework 2)。我陷入了一种情况,我需要从另一个测试类中调用一个测试类 中的方法。让我用一个小例子解释一下:从另一个测试类调用测试类的方法

<?php 
// TestUser.php 
namespace Test\User; 

class UserTest extends \PHPUnit_Framework_TestCase 
{ 

    public static function GetUserCount(){ 

     // some code here 

    } 

} 

?> 

<?php 
// TestAdmin.php 
namespace Test\Admin; 

use Test\User; 

class AdminTest extends \PHPUnit_Framework_TestCase 
{ 

    public static function AdminAction(){ 

     Test\User::GetUserCount(); 

    } 

} 

?> 

当我打电话Test\User::GetUserCount();User::GetUserCount();我收到以下错误:

PHP Fatal error: Class 'Test\User' not found in path/to/TestAdmin.php on line 11

任何想法,如果该方法是从一个测试类调用到另一个测试类?如果是,如何?

感谢

+0

类名称是:UserTest不是用户 – Pakspul

回答

1

通常情况下,你会嘲笑其他类调用,以确保返回的值是什么类期待。您也可以将一些测试与Test Dependencies连接起来。

我已经添加了一个简短的示例。请注意,我假设您添加了AdminAction和GetUserCount()作为样本,因为这些并不是您使用PHPUnit测试的真正测试方法。

TestUser.php

<?php 

namespace Test\User; 

class UserTest extends \PHPUnit_Framework_TestCase 
{ 
    protected $UserObject; 
    public function setUp() 
    { 
     $this->UserObject = new Test\User(); // Normal Object 
    } 

    public static function testGetUserCount() 
    { 
     $this->assertEquals(1, $this->UserObject->GetUserCount(), 'Testing the basic object will return 1 if initialized'); // Do your tests here. 
    } 
} 

TestAdmin.php

<?php 

namespace Test\Admin; 

class AdminTest extends \PHPUnit_Framework_TestCase 
{ 
    protected $AdminObject; 

    public function setUp() 
    { 
     $this->AdminObject = new Test\Admin(); 
    } 

    public static function testAdminAction() 
    { 
     // Create a stub for the User class. 
     $stub = $this->getMock('User'); 

     // Configure the stub. 
     $stub->expects($this->any()) 
      ->method('GetUserCount') 
      ->will($this->returnValue(2)); 

     // Calling $stub->GetUserCount() will now return 2. You can then ensure the Admin class works correctly, by changing what the mocks return. 
     $this->assertEquals(2, $stub->GetUserCount()); 
    } 

} 
相关问题