2010-11-18 157 views
0

我一直在为一个简单的Datamapper类写一个测试,并且我知道该方法正在工作,但是测试失败并且给我错误“Fatal error: Call to a member function fetchAll() on a non-object in C:\xampp\htdocs\Call log\tests\model_tests.php on line 13.”显然,这不可能是对,因为我可以验证该方法的工作原理。PHP最简单的tomfoolery。测试不通过工作方法

这里是它理应示数的代码:

function all() { 
    $calls = $this->pdo->query('SELECT * from calls'); 
    return $calls->fetchAll(); 
} 

这里是我的测试代码:

class TestOfCallMapper extends UnitTestCase { 
    function testOfReturnsAll() { 
     $this->createSchema(); 
     $mapper = Callmapper::getInstance(); 
     $results = $mapper->all(); 
     print_r($results); 
    } 

    private function createSchema() { 
     $mapper = CallMapper::getInstance(); 
     $mapper->pdo->exec(file_get_contents('../database/create_schema.sql')); 
    } 

    private function destroySchema() { 
     $mapper = CallMapper::getInstance(); 
     $mapper->pdo->exec(file_get_contents('../database/destroy_schema.sql')); 
    } 
} 

$test = new TestOfCallMapper('Test of CallMapper Methods'); 
$test->run(new HTMLReporter()); 

如果我这样做,它工作得很好:

$mapper = CallMapper::getInstance(); 
    $test = $mapper->all(); 
    print_r($test->fetchAll()); 
+0

请的var_dump()或print_r的()$测试,看看它是否真的是一个对象。 – oezi 2010-11-18 17:57:36

+0

如果你把'$ results'的var_dump的结果是(var_dump会在'bool(FALSE)'的情况下输出一些东西) – cwallenpoole 2010-11-18 18:05:25

+0

它会更容易诊断它不会在测试页面输出任何东西if我尝试print_r或var_dump $结果。在另一页上,它输出一个包含$ test的所有数据库条目的数组。 – 2010-11-18 18:11:22

回答

0

pdo查询明显失败,因此您试图在false上调用fetchAll。

我会检查它失败的原因。

+0

我意识到这一点,但它在另一页上正确返回。我能想到的唯一事情就是不知何故Simpletest使PDO查询失败。我不明白为什么或如何发生这种情况。 – 2010-11-18 18:20:39

1

您的PDO查询返回false,因此它不是PDO的实例,而是一个布尔值,请尝试这样!

function all() { 
    $calls = $this->pdo->query('SELECT * from calls'); 
    if($calls === false) 
    { 
     throw new Exception("Unable to perform query"); 
    } 
    return $calls->fetchAll(); 
} 

,然后在您TestOfCallMapper,你可以这样做:

function testOfReturnsAll() 
{ 
     $this->createSchema(); 

     $mapper = Callmapper::getInstance(); 
     try 
     { 
      $results = $mapper->all(); 
     }catch(Exception $e) 
     { 
      //Some Logging for $e->getMessage(); 
      return; 
     } 
     //Use $results here   
} 
+0

我继续前进,并做了类似的事情。它会返回以下消息: – 2010-11-18 19:53:29

+0

无法在其他未缓冲查询处于活动状态时执行查询。考虑使用PDOStatement :: fetchAll()。另外,如果你的代码只是针对mysql运行,你可以通过设置PDO :: MYSQL_ATTR_USE_BUFFERED_QUERY属性来启用查询缓冲。 – 2010-11-18 19:53:56

+0

我试着设置它在PDO构造函数中列出的属性。它没有帮助。 – 2010-11-18 19:54:32