Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Spring 4.0.3 Controller (MVC) with MockMVC

I am trying to create Test Cases for a RestController. Here is a simple RestContorller

@RestController
@RequestMapping("/media")
public class MediaListController {
    @RequestMapping(method = RequestMethod.GET)
    public String getAllMedia(){
        return "TEST COMPLETE";
    }
}

And I have a spring-rest-servlet.xml file which has <mvc:annotation-driven />

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="com.mp.web.controller.common" />

</beans>

Now if I deploy my WAR on tomcat 8 its running just as expected.

URL --> http://localhost:8080/application-name/rest/media

Now I want to create a Test Case for this REST service. What i did so far

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:spring-rest-servlet.xml")
public class MediaTest {

    MockMvc mockMvc;

    @Before
    public void init(){
        mockMvc = MockMvcBuilders.standaloneSetup(MediaListController.class).build();
    }

    @Test
    public void getAllMediaTest1() throws Exception {
        mockMvc.perform(get("/media")).andExpect(status().isOk());
    }
}

If I run that test I get the following Warning.

WARN  o.s.w.s.PageNotFound - No mapping found for HTTP request with URI [/media] in DispatcherServlet with name ''

I tried that link with other options like

'/' , '/rest/media' , 'http://localhost:8080/app-name/rest/media'

but no use.

I am using Spring 4.0.3

like image 775
Talha Ahmed Khan Avatar asked Jan 10 '23 19:01

Talha Ahmed Khan


1 Answers

You need to change your init to this :

 mockMvc = MockMvcBuilders.standaloneSetup(new MediaListController()).build();
like image 196
NimChimpsky Avatar answered Jan 19 '23 23:01

NimChimpsky