Pe4Nik
@Pe4Nik

Не работает тест для контроллера, в чем проблема?

Недавно начал изучать Spring MVC и наткнулся на проблему при написании тестов.
Постоянно выходит такая ошибка:
java.lang.AssertionError: Status
Expected: 200
Actual: 404

Тестовый класс:
ControllerTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class ControllerTest {
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext ctx;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx).build();

    }


    @Test
    public void getWordTest() throws Exception {
        mockMvc.perform(get("/test").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }

}

Контроллер:
Controller
@EnableWebMvc
@RestController
public class Controller {
    @RequestMapping(value = "/test")
    @ResponseBody
    public String getTestString() {
        return "hello";
    }
}

Конфиг:
WebConfig
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "pe4nik.config")
public class WebConfig extends WebMvcConfigurerAdapter {

}
AppInitializer
public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",
                new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("pe4nik.config");
        return context;
    }

}

Лог:
spoiler
00:16:55.276 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping'
00:16:55.276 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - No HandlerMappings found in servlet '': using default
00:16:55.279 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter'
00:16:55.285 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter'
00:16:55.285 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter'
00:16:55.299 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter'
00:16:55.301 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter'
00:16:55.638 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter'
00:16:55.638 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - No HandlerAdapters found in servlet '': using default
00:16:55.643 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver'
00:16:55.667 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver'
00:16:55.668 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver'
00:16:55.678 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver'
00:16:55.680 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver'
00:16:55.699 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver'
00:16:55.699 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - No HandlerExceptionResolvers found in servlet '': using default
00:16:55.700 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator'
00:16:55.706 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator'
00:16:55.706 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@7fee8714]
00:16:55.712 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.view.InternalResourceViewResolver'
00:16:55.774 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.view.InternalResourceViewResolver'
00:16:55.774 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - No ViewResolvers found in servlet '': using default
00:16:55.777 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.support.SessionFlashMapManager'
00:16:55.786 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.support.SessionFlashMapManager'
00:16:55.786 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager@5ba3f27a]
00:16:55.787 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Published WebApplicationContext of servlet '' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.]
00:16:55.787 [main] INFO org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 628 ms
00:16:55.787 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Servlet '' configured successfully
00:16:55.901 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - DispatcherServlet with name '' processing GET request for [/test]
00:16:55.969 [main] WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/test] in DispatcherServlet with name ''
00:16:55.969 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request
java.lang.AssertionError: Status 
Expected :200
Actual   :404
...............
  • Вопрос задан
  • 659 просмотров
Решения вопроса 1
jaxtr
@jaxtr
JavaEE/Spring-разработчик
Судя по логам, контроллер у тебя не создаётся или не регистрируется. Можно для верности в Before проверять наличие в контексте бинов класса Controller.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы