SpringMVC:在Junit中使用mockito测试Json响应

时间:2017-05-29 17:24:38

标签: java json spring-mvc junit mockito

我是一名相对较新的Java开发人员,我在线关注youtube教程以提高我的SpringMVC技能。这是教程:

https://www.youtube.com/watch?v=wmbS20Nnuq0&list=PL4gCdGOq-cxJrbRMWjrIvGhYqQO1tvYyX&index=4

作为本教程的一部分,我已经设置了一个测试类,我正在使用Junit / Mockito测试我是否可以在我的一个控制器方法中接收Json响应。但是,当我运行Junit测试时,我的测试无法接收Json数据,并且当在控制台中打印出GET请求时,我收到有关请求和响应的以下信息:

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 = []

我还在Junit收到以下例外:

  

java.lang.IllegalArgumentException:> com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:164)中的json不能为null或为空

我想解决这个异常,但我似乎无法弄明白。有人可以告诉我如何成功接收Json数据吗?

这是我的代码:

//弹簧配置文件

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;
    }
}

0 个答案:

没有答案