我所有的,我都在努力尝试正确的 TDD,但这并不是一帆风顺的。
这个测试一直失败,我不知道如何让它通过。
#>phpunit
PHPUnit 3.7.20 by Sebastian Bergmann.
Configuration read from /Users/ghall/Sites/laravel.hyundianet.hyundai.co.nz/phpunit.xml
<h2>Charts</h2>
<table class="table table-striped">
{"error":{"type":"ErrorException","message":"Invalid argument supplied for foreach()","file":"\/Users\/ghall\/Sites\/laravel.dev\/app\/storage\/views\/9fe7adcadbe887c8bce1c18e06defac2","line":8}}
我似乎是因为它试图渲染出不会从它们中退出的东西的视图模拟
路线
App::bind('App\Models\Interfaces\ChartInterface', 'App\Models\Repositories\EloquentChartRepository');
Route::resource('chart', 'ChartController');
控制器
use App\Models\Interfaces\ChartInterface;
use App\Models\Repositories\EloquentChartRepository;
class ChartController extends BaseController
{
protected $layout = 'layouts.application';
protected $chart;
function __construct(ChartInterface $chart)
{
$this->chart = $chart;
// var_dump($chart);
}
public function index()
{
$charts = $this->chart->all();
$this->layout->content = View::make('chart.index')
->with('charts', $charts);
}
}
存储库
namespace App\Models\Repositories;
use App\Models\Interfaces\ChartInterface;
use Chart;
class EloquentChartRepository implements ChartInterface
{
public function all()
{
return Chart::all();
}
public function find($id)
{
return Chart::find($id);
}
}
界面
namespace App\Models\Interfaces;
interface ChartInterface
{
public function all();
public function find($id);
}
测试
class ChartControllerTest extends TestCase
{
public function __construct()
{
$this->mock = Mockery::mock('App\Models\Interfaces\ChartInterface');
}
public function tearDown()
{
Mockery::close();
}
public function testIndex()
{
$this->mock
->shouldReceive('all')
->once()
->andReturn('charts');
$this->app->instance('App\Models\Interfaces\ChartInterface', $this->mock);
$this->call('GET', 'chart');
$this->assertViewHas('charts');
}
}
看法
@if (!empty($charts))
@section('content')
<h2>Charts</h2>
<table class="table table-striped">
@foreach ($charts as $chart)
<tr>
<td>{{ $chart->id }}</td>
<td>{{ $chart->report_name }}</td>
<td>{{ $chart->description }}</td>
<td>{{ $chart->graphtype }}</td>
<td>{{ $chart->date_range }}</td>
<td>{{ $chart->user }}</td>
</tr>
@endforeach
</table>
@stop
@else
@section('content')
<h2>Nothing to display</h2>
@stop
@endif
新 我发现了问题,它在控制器/视图中。当测试调用控制器时,控制器返回带有标记的视图。
如果我将控制器更改为 then 它可以工作,但这不是一个好的解决方案。
public function index()
{
$charts = $this->chart->all();
if(is_object($charts)){
$this->layout->content = View::make('chart.index')
->with('charts', $charts);
return;
}
return View::make('chart.test')->with('charts', $charts);
}