Laravel5.5单元测试失败:响应非视图消息问题求助
Hey there! Let's work through why your test is throwing that frustrating error. I've seen this a few times with Laravel 5.5, and it usually boils down to one of these common issues:
1. You're Missing View Assertions in Your Test
Looking at your test code, you stopped right after $this->get('/admin/news')... — Laravel needs you to explicitly assert that the response returns a view, otherwise it doesn't know you're expecting one. Here's how to complete your test properly:
public function testIndex(){ // Create 10 test news entries factory(News::class, 10)->create(); // Send the GET request and capture the response $response = $this->get('/admin/news'); // First, make sure the request succeeds (status code 200) $response->assertStatus(200); // Assert the response returns the correct view $response->assertViewIs('news.index'); // Optional: Verify the view receives the right data $response->assertViewHas('news', function($news) { return $news->count() === 10; // Check we get all 10 entries }); }
The error often pops up when you don't call assertViewIs() or similar view-related assertions — Laravel can't confirm the response is a view unless you tell it to check for that.
2. Your Route Requires Authentication (But You're Not Logged In)
If your /admin/news route uses the auth middleware (super common for admin routes), your test will get a redirect response (to the login page) instead of a view. That's why it's complaining the response isn't a view.
Fix this by simulating an authenticated user before making the request:
public function testIndex(){ // Create a test user and log them in $adminUser = factory(App\User::class)->create(); $this->actingAs($adminUser); factory(News::class, 10)->create(); $response = $this->get('/admin/news'); $response->assertStatus(200); $response->assertViewIs('news.index'); }
Double-check your routes/web.php (or admin routes file) to see if the route has middleware('auth') attached — if yes, this step is mandatory.
3. Quick Sanity Checks
Before diving deeper, rule out these simple issues:
- Verify the route exists: Make sure your
/admin/newsroute is correctly mapped toNewsController@indexin your routes file. A typo here would send your request to the wrong place. - Check the view file: Confirm
resources/views/news/index.blade.phpexists and is spelled correctly. If the view is missing, Laravel will throw an error that breaks the view response.
Give these fixes a try — most of the time, it's either missing assertions or an unauthenticated request causing the problem.
内容的提问来源于stack exchange,提问作者farhad.a

