[英]How to use PHPUnit with TestCaseTrait
我是单元测试的新手。 我阅读了文档并尝试执行相同的操作。
首先,我有下一个环境:
$ php -v
PHP 7.0.15-1+deb.sury.org~trusty+1 (cli) (built: Jan 20 2017 09:16:11) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies with Zend OPcache v7.0.15-1+deb.sury.org~trusty+1, Copyright (c) 1999-2017, by Zend Technologies
$ cat composer.json
...
"require-dev": {
"phpunit/phpunit": "^6.0",
"phpunit/dbunit": "^3.0"
},
...
我有/ src,/ tests和/ vendor目录。 Composer自动装带器工作完美。
我的PHP项目与MySQL数据库紧密结合,我只想对这些功能进行单元测试。
$ cat tests/phpunit.xml
<phpunit>
<php>
<ini name="display_errors" value="On" />
<ini name="display_startup_errors" value="On" />
</php>
</phpunit>
和测试:
$ cat tests/SimpleTest.php
<?php
use PHPUnit\Framework\TestCase;
use PHPUnit\DbUnit\TestCaseTrait;
require_once(__DIR__.'/../vendor/autoload.php');
class SimpleTest extends TestCase
{
// use TestCaseTrait;
protected function getConnection() {}
protected function getDataSet() {}
public function testFirstExample()
{
$this->assertEquals(1, 1);
}
public function testSecondExample()
{
$this->assertEquals(1, 0);
}
}
?>
$ phpunit --testdox --verbose --configuration=tests/phpunit.xml tests/SimpleTest.php
PHPUnit 6.0.6 by Sebastian Bergmann and contributors.
Runtime: PHP 7.0.15-1+deb.sury.org~trusty+1
Configuration: /home/ubuntu/workspace/tests/phpunit.xml
Simple
[x] First example
[ ] Second example
一切正常,并按预期工作,直到我取消注释该行use TestCaseTrait;
为止use TestCaseTrait;
。 从这一刻开始,测试就无法进行。 他们甚至没有在测试函数内部执行(我通过添加下一个代码进行检查: fwrite(STDERR, 'Here we are!')
)。
问题是: use TestCaseTrait;
什么问题? 声明? 为什么它破坏了整个测试? 我该如何解决?
谢谢! PS对不起,我的英语。
结论:很奇怪,但是问题出在setUp()
函数中。 您必须在测试中添加它! 当我这样做时,我的测试就可以正常工作了。
结论:很奇怪,但是问题出在setUp()函数中。 您必须在测试中添加它! 完成后,我的测试就可以正常工作
这并不奇怪,看看日志
1) SimpleTest::testFirstExample
TypeError: Argument 1 passed to PHPUnit\DbUnit\DefaultTester::__construct() must be an instance of PHPUnit\DbUnit\Database\Connection, null given, called in /x/vendor/phpunit/dbunit/src/TestCaseTrait.php on line 102
2) SimpleTest::testSecondExample
TypeError: Argument 1 passed to PHPUnit\DbUnit\DefaultTester::__construct() must be an instance of PHPUnit\DbUnit\Database\Connection, null given, called in /x/vendor/phpunit/dbunit/src/TestCaseTrait.php on line 102
那这条线呢?
# TestCaseTrait::102
return new DefaultTester($this->getConnection());
$this->getConnection()
为null
因为您已将getConnection
方法实现为protected function getConnection() {}
。
通过声明setUp
您只是重写了调用$this->getConnection()
TestCaseTrait::setUp
,这就是为什么它现在可以工作的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.