620*_*030 2 php phpunit unit-testing
我今天开始在 PhpStorm 上使用 PHPUnit 测试。我可以测试几乎所有的功能,除了需要数据库连接的功能。
功能:
public function getProductID()
{
$this->product_id = $this->db->GetOne("select product_id from table1 where id = {$this->id}");
return $this->product_id['product_id'];
}
Run Code Online (Sandbox Code Playgroud)
在我的测试用例中,出现错误:
PHP 致命错误:在 null 上调用成员函数 GetOne()
我已经定义:
global $_db;
$this->db = $_db;
Run Code Online (Sandbox Code Playgroud)
您应该在测试中模拟/存根您的连接,例如
$stub = $this
->getMockBuilder('YourDBClass') // change that value with your REAL db class
->getMock();
// Configure the stub.
$stub
->method('GetOne')
->willReturn(); // insert here what you expect to obtain from that call
Run Code Online (Sandbox Code Playgroud)
这样你的测试就与其他依赖项隔离了。
如果您想进行不同类型的测试(例如,使用 REAL DB 数据),则不应进行单元测试,而应进行功能测试或集成测试
在这里,您要测试的是getProductID()(一种方法),它应该基本上返回一个整数。时期。这是(或应该是)您测试的目的。所以你只想检查是否返回一个整数,而不是返回那个整数。如果您停下来想一想,您可能会注意到您希望不受任何其他依赖项结果的影响。
| 归档时间: |
|
| 查看次数: |
8573 次 |
| 最近记录: |