这是一个不能进行单元测试的具有硬依赖的类的例子。
我们可以通过与另一个数据库的连接进行测试,但是它不再是单元测试而是集成测试。
我想到的更好的选择是拥有一个 QueryFactory 类,它将包装您需要的所有不同方法,然后您将能够模拟它。
首先我创建一个界面
interface iQueryFactory
{
function firstFunction($argument);
function secondFunction($argument, $argument2);
}
带有我们需要的所有 ORM 请求的 QueryFactory
class QueryFactory implements iQueryFactory
{
function firstFunction($argument)
{
// ORM thing
}
function secondFunction($argument, $argument2)
{
// ORM stuff
}
}
有查询工厂注入的业务逻辑
class BusinessLogic
{
protected $queryFactory;
function __construct($queryFactoryInjection)
{
$this->queryFactory= $queryFactoryInjection;
}
function yourFunctionInYourBusinessLogique($argument, $argument2)
{
// business logique
try {
$this->queryFactory->secondFunction($argument, $argument2);
} catch (\Exception $e) {
// log
// return thing
}
// return stuff
}
}
模拟部分,请注意我的示例没有使用模拟框架(顺便说一句,您可以创建响应设置器)
class QueryFactoryMock implements iQueryFactory
{
function firstFunction($argument)
{
if (is_null($argument))
{
throw new \Exception("");
}
else
{
return "succes";
}
}
function firstFunction($argument, $argument2)
{
// sutff
}
}
最后是用模拟实现测试我们的业务逻辑的单元测试
class BusinessLogicTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
require_once "BusinessLogic.php";
}
public function testFirstFunction_WhenInsertGoodName()
{
$queryMockup = new QueryFactoryMock();
$businessLogicObject = new BusinessLogic($queryMockup);
$response = $businessLogicObject ->firstFunction("fabien");
$this->assertEquals($response, "succes");
}
public function testFirstFunction_WhenInsetNull()
{
$queryMockup = new QueryFactoryMock();
$businessLogicObject = new BusinessLogic($queryMockup);
$response = $businessLogicObject->firstFunction(null);
$this->assertEquals($response, "fail");
}
}