PHP最简单的tomfoolery。测试没有传递工作方法

时间:2010-11-18 17:55:31

标签: php simpletest

我一直在为一个简单的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.”显然,这不可能是正确的,因为我可以验证该方法是否有效。

以下是它应该错误的代码:

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());

2 个答案:

答案 0 :(得分: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        
}

答案 1 :(得分:0)

pdo查询显然是失败的,因此你试图在false时调用fetchAll。

我会检查它失败的原因。