以不同的方法使用预先创建的Slim环境


use pre created Slim environment in different methods

我正在用phpunit为几个类编写一些测试。每个类都有以下方法:

  function getDbh() {
    if ($this->dbh === null){
      $this->dbh = Slim::getInstance()->db->getConnection();
    }
    return $this->dbh;
  }

但问题是,在第一次测试之后,我创建了这个环境单例,我不知道我可以在接下来的测试中使用。

为了使我的具体问题更清楚一些,我的每个测试类都有这个方法:

public function testGetDbh_dbhIsNull()
{
    $fixture = new testedClass();
    $app = new Slim();
    $DB = $this->getMockBuilder('DB')
                 ->disableOriginalConstructor()
                 ->getMock();
    $DB->method('getConnection')->willReturn('connection');
    $app->db = $DB;
    $this->assertEquals($fixture->getDbh(), 'connection');
}

但是从第二次测试中,由于以下错误,测试失败:

1) GroupTest::testSlim
Failed asserting that 'connection' matches expected null.

知道如何在每个测试中使用Slim单例吗?thx

你的测试是错误的:)

public function testGetDbh_dbhIsNull()
{
    $fixture = new testedClass();
    $app = new Slim();
    $DB = $this->getMockBuilder('DB')
                 ->disableOriginalConstructor()
                 ->getMock();
    $DB->method('getConnection')->willReturn('connection');
    $app->db = $DB;
    //This points to the wrong object... This should fix it
    $this->assertEquals($app->db, 'connection');
}