我已经写了一个简单的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());
有帮助吗?

解决方案

在PDO查询很明显没有,所以你尝试呼叫使用fetchall虚假。

我要检查它为什么失败。

其他提示

您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        
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top