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/[email protected]").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/[email protected]").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
It works fine
Update
http://localhost:8080/my-service/api/[email protected]
Could some one tell me What's wrong here ???
The class will handle the HTTP request and pass it further to our controller. Controller code will be executed in exactly the same way as if it was processing the real request, just without the cost of starting a web server. MockMvc also carries several useful methods for performing requests and asserting on results.
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/[email protected]") .contextPath ("/my-service") .accept (MediaType.APPLICATION_JSON)) .andExpect (status ().isOk ());
Yes, because when you adding context path to the mvc perform, you have to request to the URI with contextPath prefix. Yeah, I just saw I do mistake in answer in get ("...").
MockMvc also carries several useful methods for performing requests and asserting on results. Here’s an example of building a test class with MockMvc. This class will test the DoctorController visible above.
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/[email protected]")
.contextPath("/my-service")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With