将参数传递给SimpleTest单元测试

时间:2013-01-09 03:25:50

标签: php simpletest

我有一个班级,我正在编写使用SimpleTest的测试。类中有静态函数需要传递我的SQL连接对象,它驻留在Variables.php中。我该怎么做?

<?
   require_once('../Variables.php');


   class TestOfMember extends UnitTestCase {

      function testGetMembersFromEmailAddress() {

         $this->assertTrue($Member::getMembersFromEmailAddress("xxx@xxx.com", $conn)==null);
         $this->assertTrue($Member::getMembersFromEmailAddress("xxx@gmail.com", $conn)!=null);
      }
    }

?>


class Member {
public static function getMembersFromEmailAddress($emailAddress, $conn) {

    $args = array();
    $args[] = $conn;

    try {
        $result = $conn->query("SELECT * FROM members WHERE Members_Email ='" . $emailAddress . "'");
        $members = $result->fetchAll(PDO::FETCH_CLASS, 'Member', $args);

        return $members;
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

}

1 个答案:

答案 0 :(得分:0)

您所描述的是一个典型问题。解决它的最简单方法是使用所谓的模拟对象。这些对象的行为就像它们是一个真实的对象,但事实上它们只是一个薄壳。另外:您可以在测试中完全控制它们。

使用模拟对象有不同的方法SimpleTest even has it's own implementation。或者你可以使用像mockery这样的框架。

在您的情况下,您需要一个带有DatabaseConnection方法的数据库连接对象(query())。这将返回一个结果对象(Result),该对象又具有fetchAll()方法,并且可能返回一个数组。

我首先声明两个接口,这允许SimpleTest模拟方法。如果您已经为它们声明了类,则可以在Mock::generate()中使用它们来生成模拟类。

interface DatabaseConnection
{
    function query();
}

interface Result
{
    function fetchAll();
}

//this call generates a class called 'MockDatabaseConnection'
//with the same interface as 'DatabaseConnection'
Mock::generate('DatabaseConnection');
Mock::generate('Result');

class TestOfMember extends UnitTestCase
{
   //this method gets called before each test method, it sets up each test
   function setUp() {
       $mockResult = new MockResult();
       //here I just return a string, but you could return a Member object as well
       $mockResult->returns('fetchAll', array("Member 1", "Member 2", "Member 3"));
       $this->mockConn = new MockDatabaseConnection();
       $this->mockConn->returns('query', $mockResult);
   }

   function testGetMembersFromEmailAddress() {
       $conn = new MockDatabaseConnection();

       //here you could now check for the mocked values "Member 1", "Member 2" ...
       $this->assertTrue(Member::getMembersFromEmailAddress("xxx@xxx.com", $this->mockConn)==null);
       $this->assertTrue(Member::getMembersFromEmailAddress("xxx@gmail.com", $this->mockConn)!=null);
   }
}