0

我有一堂课,我正在编写使用 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();
    }
}

}

4

1 回答 1

0

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

使用模拟对象有不同的方法,SimpleTest 甚至有它自己的实现。或者你可以使用像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);
   }
}
于 2013-01-10T00:44:19.510 回答