Home > Software engineering >  Spring Boot Unit Test returns 404 instead of 200
Spring Boot Unit Test returns 404 instead of 200

Time:08-26

I am new in springboot. I am just watching the img1

after google that i realized it might not find my controller so I add @Import(HomeController.class) to the test class. It looks like:

package com.qph.tacos;

import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@WebMvcTest(HomeControllerTest.class)
@Import(HomeController.class)
public class HomeControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testHomePage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.view().name("home"))
                .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("Welcome to...")));
    }
}

then it just pass the test!!!

now i just wonder why the code written by the author can pass the test without @Import(HomeController.class)?

my directory structure is like:

directories

the controller to be tested is:

package com.qph.tacos;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        // return the name of template
        return "home";
    }
}

I am new in springboot. maybe it's a simple question but i really spent so much time on it.

Thanks for your help!

CodePudding user response:

Change to

@WebMvcTest(HomeController.class)

You should reference the controller under test with this annotation, otherwise it won't be loaded into the application context.

  • Related