0
votes

I am trying to add unit testing for my spring boot application. It doesn't work, and throws 404. I am using 1.2.1 release spring boot and have dependencies for spring-boot-starter-test. Please let know if i am missing something. The spring boot app works without any issue.

Here is my code,

public class Application{

    public static void main(String[] args) {//NOSONAR
        SpringApplication.run(Application.class, args);
    }
       @Bean
    public ServletRegistrationBean displayListServletRegistrationBean(){
        return new ServletRegistrationBean(new DisplayServlet(),"/display");
    }
    @Bean
    public ServletRegistrationBean manageServletRegistrationBean(){
        return new ServletRegistrationBean(new ManageServlet(),"/manage");
    }

}

My junit test case code,

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-test-context.xml"})
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@WebIntegrationTest({"server.port=0", "management.port=0"})
@ActiveProfiles("scratch")

public class ApplicationTest {
    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setUp() {
        this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
    }

    @Test
    public void testHome() throws Exception {
        this.mvc.perform(get("/display")).andExpect(status().isOk());
        //this.mvc.perform(get("/")).andExpect(status().isOk());
    }

}

The console has

org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/display] in DispatcherServlet with name ''

and Junit result has

java.lang.AssertionError: Status expected:<200> but was:<404> at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
1

1 Answers

1
votes

Spring MVC Test is only designed for testing requests that are handled by Spring MVC's DispatcherServlet. It doesn't know anything about your DisplayServlet which is why, as shown in the log, the DispatcherServlet has tried to handle the request rather than your DisplayServlet.

There are a few different ways in which you could proceed. For example:

  1. You could change your application to wrap your servlets using ServletWrappingController so that Spring MVC knows about them.
  2. You could change your testing approach and use RestTemplate against a real server. You're actually already starting a real server by virtue of the WebIntegrationTest annotation on your test class.