springMVC的单元测试

Controller层

@Controller
public class BookController {
    @Autowired
    private BookService bookService;
    private static final Log logger = LogFactory.getLog(BookController.class);

    @RequestMapping(value = "/book_edit/{id}")
    public String editBook(Model model, @PathVariable long id) {
        System.out.println(id);
        Book book = bookService.get(id);
        model.addAttribute("book", book);
        return "BookEditForm";
    }

    @RequestMapping(value = "/book_save" ,method = RequestMethod.POST)
    public String saveBook(@ModelAttribute Book book) {
        //bookService.save(book);
        return "redirect:/book_list";
    }

    @RequestMapping(value = "/book_list",method = RequestMethod.GET)
    public String listBooks(Model model) {
        logger.info("book_list");
        System.out.println("book_list start excute!!");
        List<Book> books = bookService.getAllBooks();
        model.addAttribute("books", books);
        return "BookList";
    }
}

模拟的测试类

package cm.yanxi.test;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

<!---这几个常量很重要,必须引入-->
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.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
/**
 * Created by 言溪 on 2016/11/10.
 */
@RunWith(SpringJUnit4ClassRunner.class)

//表示测试环境使用的ApplicationContext将是WebApplicationContext类型的;value指定web应用的根

@WebAppConfiguration("src/main/webapp")
@ContextConfiguration(locations = {"classpath:spring-common.xml","classpath:spring-mvc.xml"})

public class BookControllerTest {

//    注入web环境的ApplicationContext容器

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void setup() throws  Exception{

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/html/");
        viewResolver.setSuffix(".jsp");

        this.mockMvc=webAppContextSetup(this.webApplicationContext).build();
    }

    @Test
    public void saveBookTest() throws Exception {
        this.mockMvc.perform(
                post("/book_save")
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                        .param("category","计算机科学")
                        .param("title","大数据集群")
                        .param("author","kangkang")
                        .param("isbn","123456"))
                .andDo(print())
                .andExpect(redirectedUrl("/book_list"))
                .andReturn();
    }

    @Test
    public void BookListTest() throws Exception {
        this.mockMvc.perform(get("/book_list"))
                .andDo(print())
                .andExpect(view().name("BookList"))
                .andReturn();
    }

    @Test
    public void BookEditTest() throws Exception {
        this.mockMvc.perform(get("/book_edit/{id}","3"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(view().name("BookEditForm"))
                .andExpect(model().attribute("book",""))
                .andReturn();
    }


}

更多的模拟请求案例点这里

##解释一下几个参数的含义

  • mockMvc.perform执行一个请求; 
  • MockMvcRequestBuilders.get("/book_edit/{id}")构造一个请求 
  • ResultActions.andExpect添加执行完成后的断言 
  • ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情,例如使用
    • MockMvcResultHandlers.print()输出整个响应结果信息。
  • ResultActions.andReturn表示执行完成后返回相应的结果。

测试结果显示

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /book_edit/3
       Parameters = {}
          Headers = {}

Handler:
             Type = com.yanxi.controller.BookController
           Method = public java.lang.String com.yanxi.controller.BookController.editBook(org.springframework.ui.Model,long)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = BookEditForm
             View = null
        Attribute = book
            value = Book{id=3, isbn='9787115386397', title='HTML5实战', category='计算机编程', author='Marco Casario'}
           errors = []

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = /html/BookEditForm.jsp
   Redirected URL = null
          Cookies = []

转载于:https://my.oschina.net/lcyanxi/blog/786835

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值