如何使用MDB2和PHPUnit DataBase进行多次测试?

时间:2021-11-22 07:17:57

I use PHPUnit DataBase to test some class using MDB2.

我使用PHPUnit DataBase来测试一些使用MDB2的类。

All is well, since I encounter the second test, which returns an error:

一切都很好,因为我遇到第二个测试,它返回一个错误:

Caught exception: Object of class MDB2_Error could not be converted to string

捕获异常:类MDB2_Error的对象无法转换为字符串

When I place the second test in place of the first one, the new first test is OK, but the second one returns the same error! And the next ones also!

当我将第二个测试放在第一个测试的位置时,新的第一个测试是正常的,但第二个测试返回相同的错误!还有下一个!

Maybe the MDB2 connection is closed after the first test?

也许MDB2连接在第一次测试后关闭了?

Here is my constructor:

这是我的构造函数:

public function __construct()
{
    $this->pdo = new PDO('connectionstring', 'user', 'passwd');
    try {
        $this->mdb2 = new MyDBA($this->dsn);
    }
    catch (Exception $e) {
        error_log(' __construct Caught exception: '.$e->getMessage());
    }
}

MyDBA returns a singleton. No exception is raised inside the constructor...

MyDBA返回一个单身人士。构造函数中没有引发异常......

Here are the two first tests:

以下是两个首次测试:

public function testTranslationAdd()
{
    try {
        $id = $this->mdb2->addTranslation("This is the second english translation.","en");
    }
    catch (Exception $e) {
        error_log(' testTranslationAdd Caught exception: '.$e->getMessage());
    }

    $xml_dataset = $this->createFlatXMLDataSet(dirname(__FILE__).'/state/twotranslations.xml');
    $this->assertDataSetsEqual($xml_dataset,
                               $this->getConnection()->createDataSet(array("translation")));
}

public function testTranslationGet()
{
    try {
        $text = $this->mdb2->getTranslation(1,"en");
    }
    catch (Exception $e) {
        error_log(' testTranslationGet Caught exception: '.$e->getMessage());
    }

    $this->assertEquals("This is the first english translation.",$text);
}

1 个解决方案

#1


You should really add assertions that your mdb2 result is no error:

你应该添加断言你的mdb2结果没有错误:

$this->assertFalse(MDB2::isError($this->mdb2), 'MDB2 error');

That unfortunately does not give you any hint what the error is, and using getMessage() directly in the assertion will fail badly if you don't have an error. That why you should write something along that way:

遗憾的是,并没有给出任何提示错误,并且如果没有错误,在断言中直接使用getMessage()将会失败。这就是为什么你应该这样写的东西:

if (MDB2::isError($this->mdb2)) {
    $this->fail('MDB2 error: ' . $this->mdb2->getMessage());
}

#1


You should really add assertions that your mdb2 result is no error:

你应该添加断言你的mdb2结果没有错误:

$this->assertFalse(MDB2::isError($this->mdb2), 'MDB2 error');

That unfortunately does not give you any hint what the error is, and using getMessage() directly in the assertion will fail badly if you don't have an error. That why you should write something along that way:

遗憾的是,并没有给出任何提示错误,并且如果没有错误,在断言中直接使用getMessage()将会失败。这就是为什么你应该这样写的东西:

if (MDB2::isError($this->mdb2)) {
    $this->fail('MDB2 error: ' . $this->mdb2->getMessage());
}