I am a relatively new Java developer and I am following a youtube tutorial online to improve my SpringMVC skills. Here is the tutorial:
https://www.youtube.com/watch?v=wmbS20Nnuq0&list=PL4gCdGOq-cxJrbRMWjrIvGhYqQO1tvYyX&index=4
As part of the tutorial, I have set up a test class and I am using Junit / Mockito to test whether I can receive a Json response in one of my controller methods. However, when I run the Junit test, my test is failing to receive the Json data and when the GET request is printed out in the console, I am receiving the following information on the request and response:
WARNING: No mapping found for HTTP request with URI [rest/blog-entries/1] in DispatcherServlet with name ''
MockHttpServletRequest:
HTTP Method = GET
Request URI = rest/blog-entries/1
Parameters = {}
Headers = {}
Handler:
Type = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
I also received the following exception in Junit:
java.lang.IllegalArgumentException: json can not be null or empty at >com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:164)
I want to resolve this exception however, I can't seem to figure it out. Can somebody advise me on how to successfully receive the Json data?
Here is my code:
//spring config file
package spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan(basePackages="com.webapp.Spring")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
//BlogEntryController.class
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import spring.core.entities.BlogEntry;
import spring.core.services.BlogEntryService;
import spring.rest.resources.BlogEntryResource;
import spring.rest.resources.asm.BlogEntryResourceAsm;
@Controller
@RequestMapping("rest/blog-entries")
public class BlogEntryController {
private BlogEntryService service;
public BlogEntryController(BlogEntryService service){
this.service = service;
}
@RequestMapping(value="/{blogEntryId}",
method = RequestMethod.GET)
public ResponseEntity<BlogEntryResource> getBlogEntry(
@PathVariable Long blogEntryId) {
BlogEntry entry = service.find(blogEntryId);
if(entry != null)
{
BlogEntryResource res = new BlogEntryResourceAsm().toResource(entry);
return new ResponseEntity<BlogEntryResource>(res, HttpStatus.OK);
} else {
return new ResponseEntity<BlogEntryResource>(HttpStatus.NOT_FOUND);
}
}
}
//BlogEntryControllerTest.class
package spring.rest.mvc;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import spring.core.entities.BlogEntry;
import spring.core.services.BlogEntryService;
import spring.rest.mvc.BlogEntryController;
@RunWith(MockitoJUnitRunner.class)
public class BlogEntryControllerTest {
@InjectMocks
private BlogEntryController controller;
@Mock
private BlogEntryService service;
private MockMvc mockMVC;
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
mockMVC = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void getExistingBlogEntry() throws Exception {
BlogEntry entry = new BlogEntry();
entry.setId(1L);
entry.setTitle("Test Title");
when(service.find(1L)).thenReturn(entry);
mockMVC.perform(get("rest/blog-entries/1"))
.andDo(print())
.andExpect(jsonPath("$.title", is(entry.getTitle())))
.andExpect(jsonPath("$.links[*].href", hasItem(endsWith("/blog-entries/1"))))
.andExpect(status().isOk());
}
}
//BlogEntryResource.class
import org.springframework.hateoas.ResourceSupport;
import spring.core.entities.BlogEntry;
public class BlogEntryResource extends ResourceSupport {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BlogEntry getBlogEntry() {
BlogEntry entry = new BlogEntry();
entry.setTitle(title);
return entry;
}
}