关于单元测试的controller的调用
我的分页的controller
package controller;
import bean.Client;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import service.ClientService;
import java.util.List;
@Controller
public class ClientController {
@Autowired
ClientService clientService;
@RequestMapping("/clis")
public String getClis(@RequestParam(value="pn",defaultValue = "1")Integer pn, Model model){
PageHelper.startPage(pn,5);
List<Client> clis=clientService.getAll();
PageInfo page=new PageInfo(clis,5);
model.addAttribute("pageInfo",page);
return "list";
}
}
单元测试
package test;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
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.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import bean.Client;
import com.github.pagehelper.PageInfo;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations ={"classpath:applicationContext.xml","file:E:\\test\\MacenDemo\\src\\main\\webapp\\WEB-INF\\dispatcherServlet-servlet.xml"})
public class MvcTest {
@Autowired
WebApplicationContext context;
MockMvc mockMvc;
@Before
public void initMockMvc(){
mockMvc=MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testPage() throws Exception{
MvcResult result= mockMvc.perform(MockMvcRequestBuilders.get("/clis").param("pn","5")).andReturn();
MockHttpServletRequest request=result.getRequest();
PageInfo pi= (PageInfo) request.getAttribute("pageInfo");
System.out.println("当前页码:"+ pi.getPageNum());
System.out.println("总页码:"+ pi.getPages());
System.out.println("总记录数:"+ pi.getTotal());
System.out.println("在页面需要连续显示的页码");
int[] nums=pi.getNavigatepageNums();
for(int i:nums){
System.out.println(" "+i);
}
List<Client> list=pi.getList();
for(Client client:list){
System.out.println("ID:"+client.getId()+"==>Name"+client.getClientname());
}
}
}
异常代码
java.lang.NullPointerException
at test.MvcTest.testPage(MvcTest.java:39)
也就是没有取到pi的值,pi为空
ClientController 显示Class 'ClientController' is never used
求大神指导,已经研究两天了,谢谢你们了