代码之家  ›  专栏  ›  技术社区  ›  afkbowflexin

php-simpletest-tombuery。测试不通过工作方法

  •  0
  • afkbowflexin  · 技术社区  · 14 年前

    我一直在为一个简单的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 回复  |  直到 14 年前
        1
  •  0
  •   mhughes    14 年前

    pdo查询显然失败了,因此您试图在false上调用fetchall。

    我会查一下为什么会失败。

        2
  •  1
  •   RobertPitt    14 年前

    您的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        
    }
    
    推荐文章