phpunit - 无法调用依赖测试用例

标签 phpunit

我正在编写单元测试来测试模型类。 首先,我有一个 testAddStudent() 测试用例,它将一些数据添加到数据库中。 然后我有另一个测试用例来检索我刚刚添加的记录。 我的代码如下所示:

class Model_STest extends PHPUnit_Framework_TestCase {

protected $_student;

public function setUp() {
    error_log("Entered setup");
    parent::setUp();

    $this->_student = new Application_Model_Student();
}

public function testInit() {
    error_log("Entered testInit");
}

public function testAddStudent() {
    error_log("Entered testAddStudent");
    $testData = array(
            'name' => 'abc',
            'teacher' => 'amyac',
            'start_date' => '2012_08_06'
            );

    $result = $this->_student->addStudent($testData);
    error_log("result is ".print_r($result, true));
    $this->assertGreaterThan(0, $result);
}

/**
 * @depends testAddStudent
 */
public function testGetStudent($result) {
    error_log("Entered testGetStudent, finding student id: $result");
    $resultx = $this->_student->getStudent($result);
    $this->assertEquals($result, $resultx);
    }

}

但是,当我运行 phpunit 测试(使用命令行)时,日志显示正在搜索的学生 ID 为 0。而 testAddStudent 返回的学生 ID 为非零值。

我做错了什么? 我有

PHPUnit 3.6.11 by Sebastian Bergmann.

非常感谢任何帮助。

谢谢!

最佳答案

您应该从 testAddStudent() 函数返回 $result

(被依赖函数的返回值被传递给依赖函数。)

您还可以考虑对 Application_Model_Student 实例执行相同的操作,而不是使用 protected 类变量。这是您重写的示例以表明这一点。 (我使用了一个虚拟的 Application_Model_Student,它的性能足以通过测试。)

class Application_Model_Student{
private $d;
function addStudent($d){$this->d=$d;return 1;}
function getStudent($ix){return $ix;}
}

//----------------------
class Model_STest extends PHPUnit_Framework_TestCase {

public function testAddStudent() {
    error_log("Entered testAddStudent");

    $testData = array(
            'name' => 'abc',
            'teacher' => 'amyac',
            'start_date' => '2012_08_06'
            );

    $student = new Application_Model_Student();
    $result = $student->addStudent($testData);
    error_log("result is ".print_r($result, true));
    $this->assertGreaterThan(0, $result);
    return array($student,$result);
}

/**
 * @depends testAddStudent
 */
public function testGetStudent($data) {
    list($student,$result)=$data;
    error_log("Entered testGetStudent, finding student id: $result");
    $resultx = $student->getStudent($result);
    $this->assertEquals($result, $resultx);
    }

}

附注请注意我用于 getStudent 的实现以使其通过!我想这不是您想要做的测试。

关于phpunit - 无法调用依赖测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11836226/

相关文章:

intellij-idea - IntelliJ IDEA 不会运行 PHPUnit 4.0 测试

--coverage-html 时 Phpunit 非常慢

php - fatal error : Class 'ZipArchive' - not found when using PHPUnit

php - 如何在 PHPUnit 中查找风险测试的原因

php - 如何让 Netbeans PHPUnit 代码覆盖率在 Windows 上运行?

php - 单元测试类 - 抛出错误是不可能的吗?

kohana - PHPUnit + Kohana : Undefined index: HTTP_HOST

PHPUnit 和扩展类

Laravel 中的 PHPUnit 错误 : Exception' with message 'SQLSTATE[HY000] [2005] Unknown MySQL server host ' mysql' (2)'

cmd - 在没有/vendor/bin/的 laravel 4 中使用 phpunit