これは、単体テストできない強い依存関係を持つクラスの例です。
別のデータベースへの接続をテストすることはできますが、それは単体テストではなく、統合テストになります。
私が考えるより良い代替案は、必要なすべての異なるメソッドをラップする 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");
}
}