我在努力学习我所写的测试的实用性。事实上,我不太确定我写的测试是否正确。我有一个具有函数where($q, $count)
的存储库类,其中' q'是一个查询字符串,count是我期望返回的结果数。该功能取决于我的ORM。我希望在ORM上调用几个函数。我使用Mockery来模拟对ORM对象的依赖。我写了一个测试来验证我只查询4个特定字段。以下是测试后面的函数:
public function where($q, $count)
{
if(is_null($count))
{
$count = 100;
}
$query = '%'.$q.'%';
$contracts = $this->contractModel
->where('contractNumber', 'like', $query)
->orwhere('customerName', 'like', $query)
->orWhere('customerId', 'like', $query)
->orwhere('contractName', 'like', $query)
->paginate($count, [ 'contractNumber', 'contractName', 'revision', 'customerId', 'customerName' ]);
$this->assignContractAPIUrlToResults($contracts);
$modifiedPagerResults = $this->queryHelper->setupAdditionalPageOptions($contracts, $count);
return $modifiedPagerResults;
}
public function it_should_query_different_fields()
{
$eloquentBuilder = m::mock('Illuminate\Database\Eloquent\Builder');
$queryBuilder = m::mock('Illuminate\Database\Query\Builder');
$paginator = m::mock('\Illuminate\Pagination\Paginator');
$this->contractModelMock->shouldReceive('where')->once()->with('contractNumber', 'like', '%foo%')->andReturn($eloquentBuilder);
$eloquentBuilder->shouldReceive('orWhere')->once()->with('customerName', 'like', '%foo%')->andReturn($eloquentBuilder);
$eloquentBuilder->shouldReceive('orWhere')->once()->with('customerId', 'like', '%foo%')->andReturn($eloquentBuilder);
$eloquentBuilder->shouldReceive('orWhere')->once()->with('contractName', 'like', '%foo%')->andReturn($queryBuilder);
$paginationResultContainer = [
'contractNumber',
'contractName',
'revision',
'customerId',
'customerName'
];
$queryBuilder->shouldReceive('paginate')->once()->with(5, $paginationResultContainer)->andReturn($paginator);
$paginator->shouldReceive('getItems')->once()->andReturn([]);
$this->queryResultHelperMock->shouldReceive('setupAdditionalPageOptions')->once()->with($paginator, 5);
$this->contractRepository->where('foo', 5);
}
我这样做错了吗?我已经读过单元测试不应该测试实现细节,但我怎么测试我特别想要查询4个字段而只有4个字段?因为我的函数主要只调用依赖函数,感觉这个函数可能不需要测试吗?使用PHPUnit,我无法让测试通过而不告诉测试应该在依赖项上调用哪些函数以及它们应该返回什么函数。