5

I have a GET method in my REST API

This is my controller class

@RestController
@RequestMapping("/api")
@Validated
public class ApiController {

@Autowired
private ApiService service;

@GetMapping(path = { "/check/{type}", "/check" }, 
produces= {MediaType.APPLICATION_JSON_UTF8_VALUE,MediaType.APPLICATION_XML_VALUE})
    public List<Myobject> check(@MyConstraint @RequestParam("email") final List<String> emails,
            @PathVariable(name = "type", required = false) final String type) {
        final String subscriptiontype = StringUtils.isEmpty(type) ? "all" : type;
        final List<Myobject> objects= service.check(emails, subscriptiontype);

    return objects;
}

}

I'm trying to write a Unit Test For this controller class

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SubscriberApiController.class)

public class ApiControllerTest {

private MockMvc mvc;

@Autowired
private WebApplicationContext webApplicationContext;

@MockBean
private ApiService service;

@Before
public void setUp() {
//  mvc = MockMvcBuilders.standaloneSetup(new HandlerController()).build();
    mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@Test
public void getIndex() throws Exception {
    mvc.perform(get("/my-service/api/check?email=someone@someone.com").accept(MediaType.APPLICATION_JSON))
       .andExpect(status().isOk());

}
}

But it's showing me mapping error No mapping found for HTTP request with URI

2018-04-20 11:51:23.409  INFO 12968 --- [           main] c.a.d.s.service.api.ApiControllerTest    : No active profile set, falling back to default profiles: default
    2018-04-20 11:51:23.432  INFO 12968 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@43f02ef2: startup date [Fri Apr 20 11:51:23 BST 2018]; root of context hierarchy
    2018-04-20 11:51:24.847  INFO 12968 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/check/{type} || /api/check],methods=[GET],produces=[application/json;charset=UTF-8 || application/xml]}" onto public com.aerlingus.dei.subscriber.service.api.model.Subscriptions com.aerlingus.dei.subscriber.service.api.controller.SubscriberApiController.checkSubscriptionForUSersByType(java.util.List<java.lang.String>,java.lang.String)
    2018-04-20 11:51:24.852  INFO 12968 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
    2018-04-20 11:51:24.852  INFO 12968 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
    2018-04-20 11:51:24.944  INFO 12968 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@43f02ef2: startup date [Fri Apr 20 11:51:23 BST 2018]; root of context hierarchy
    2018-04-20 11:51:24.993  INFO 12968 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in badRequestExceptionHandler
    2018-04-20 11:35:47.040  INFO 30276 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@43f02ef2: startup date [Fri Apr 20 11:35:44 BST 2018]; root of context hierarchy
    2018-04-20 11:35:47.110  INFO 30276 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in badRequestExceptionHandler
    2018-04-20 11:35:47.454  INFO 30276 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
    2018-04-20 11:35:47.454  INFO 30276 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization started
    2018-04-20 11:35:47.475  INFO 30276 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization completed in 21 ms
    2018-04-20 11:35:47.625  INFO 30276 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
    2018-04-20 11:35:47.626  INFO 30276 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
    2018-04-20 11:35:47.656  INFO 30276 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
    2018-04-20 11:35:47.702  INFO 30276 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
    2018-04-20 11:35:47.938  INFO 30276 --- [           main] .d.s.w.r.o.CachingOperationNameGenerator : Generating unique operation named: checkSubscriptionForUSersByTypeUsingGET_1
    2018-04-20 11:35:47.960  INFO 30276 --- [           main] c.a.d.s.s.api.HandlerControllerTest      : Started HandlerControllerTest in 3.653 seconds (JVM running for 4.761)
    2018-04-20 11:35:47.983  INFO 30276 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
    2018-04-20 11:35:47.983  INFO 30276 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization started
    2018-04-20 11:35:47.985  INFO 30276 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization completed in 2 ms
    2018-04-20 11:35:48.031  WARN 30276 --- [           main] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/my-service/api/check] in DispatcherServlet with name ''
    2018-04-20 11:35:48.050  INFO 30276 --- [       Thread-2] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@43f02ef2: startup date [Fri Apr 20 11:35:44 BST 2018]; root of context hierarchy
    2018-04-20 11:35:48.052  INFO 30276 --- [       Thread-2] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 2147483647

My ciontext root is not getting mapped to servlet

server.servlet.contextPath=/my-service

if I change test to

 mvc.perform(get("/api/check?email=someone@someone.com").accept(MediaType.APPLICATION_JSON))
       .andExpect(status().isOk());

It works fine

Update

http://localhost:8080/my-service/api/check?email=someone@someone.com

Could some one tell me What's wrong here ???

edwin
  • 7,985
  • 10
  • 51
  • 82

2 Answers2

6

The MockMvc is a mock and it is not load context path from the server configuration. You must add contextPath to your mockMvc object:

mvc.perform(get("/my-service/api/check?email=someone@someone.com")
    .contextPath("/my-service")
    .accept(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk());
Adam Lesiak
  • 501
  • 4
  • 10
  • Well it think it's something around registering the servlet, still i tried what you suggested got 'java.lang.IllegalArgumentException: Request URI [/api/check] does not start with context path [/my-service]'. – edwin Apr 20 '18 at 12:07
  • Try my second answer, without .contextPath("/my-service") in mockMvc perform. – Adam Lesiak Apr 20 '18 at 12:17
  • Yes, because when you adding context path to the mvc perform, you have to request to the URI with contextPath prefix. – Adam Lesiak Apr 20 '18 at 12:31
  • Yeah, I just saw I do mistake in answer in get("..."). I just corrected it. – Adam Lesiak Apr 20 '18 at 12:44
  • `.contextPath("/my-service")` did the trick for me, thank you! – dkb Dec 12 '19 at 16:02
0

The configuration in wrong. Replace:

server.servlet.contextPath=/my-service

with:

server.contextPath=/my-service
Adam Lesiak
  • 501
  • 4
  • 10