• Javaspring+mybit+maven中实现Junit测试类


    在一个Javaspring+mybit+maven框架中,增加Junit测试类。

    在测试类中遇到的一些问题,利用spring 框架时,里面已经有保密security+JWT设定的场合,在你的security文件中,添加你的URI路径,且确保完全一致,缺省的话是不可以的。

    例如:

    URI:aaaaa/bbb   security文件中定义:aaaaa/** 的场合,测试类访问的时候会出现错误status:302

    这种场合你就要尝试利用完全一致的写法来试验一下。

    系统:window7

    1.首先在配置文件pom.xml文件中添加测试类的包文件,之后执行maven取得相对应的包文件到本地

         <dependency><!-- JUnit单元测试框架 -->  
    	    <groupId>junit</groupId>  
    	    <artifactId>junit</artifactId>  
    	    <version>4.12</version>  
    	    <scope>test</scope>  
    	</dependency>  
    	<dependency><!-- spring对测试框架的简单封装功能 -->  
    	    <groupId>org.springframework</groupId>  
    	    <artifactId>spring-test</artifactId>  
    	    <version>${spring.version}</version>  
    	    <scope>test</scope>  
    	</dependency>
    	<dependency>  <!--- mock追加->
    	    <groupId>org.mockito</groupId>  
    	    <artifactId>mockito-core</artifactId>  
    	    <version>1.9.5</version>  
    	    <scope>test</scope>  
    	</dependency> 
    

     测试类

    场合1:当你的Controller里面没有用到session

    package com.cnc.mht;
    
    import static org.mockito.Mockito.*;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.mock.mockito.MockBean;
    import org.springframework.http.MediaType;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    import java.util.List;
    import java.util.Map;
    import com.cnc.mht.web.http.RequestUtil;
    import com.cnc.mht.web.weixin.dto.ImsWcyMakeAnAppointment;
    import net.sf.json.JSONObject;
    
    @SpringBootTest
    @RunWith(SpringJUnit4ClassRunner.class)
    public class SpringJunitTest {
    	@Autowired
    	private WebApplicationContext webApplicationContext;
    	private MockMvc mockMvc;
    	@Autowired
    	JdbcTemplate jdbctemplate = null;
    
    //	@Inject
    	@MockBean
    //	@Autowired
    	RequestUtil requestUtil;
    
    	@Before
    	public void setUp() throws Exception {
    		mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    	}
    
    	@Test
    	public void testComment() throws Exception {
    		// parmがない
    		String responseString = mockMvc
    				.perform(MockMvcRequestBuilders.post("/openSesame").contentType(MediaType.APPLICATION_JSON_VALUE))
    				.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    
    		System.out.println("哈哈哈" + responseString);
    	}
    
    	@Test
    	public void testComment1() throws Exception {
    		// parmがある
    		String responseString = mockMvc
    				.perform(MockMvcRequestBuilders.post("/openSesame/getTableInfos")
    						.contentType(MediaType.APPLICATION_JSON_VALUE).param("weid", "11").param("bussinessid", "1")
    						.param("storeid", "53").param("date", "20190901"))
    				.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    
    		System.out.println("哈哈哈" + responseString);
    	}
    
    	@Test
    	public void testComment2() throws Exception {
    		// DB検索
    		List<Map<String, Object>> aa = jdbctemplate.queryForList("select * from ims_wcy_mst_code");
    		ImsWcyMakeAnAppointment imsWcyMakeAnAppointment = new ImsWcyMakeAnAppointment();
    		imsWcyMakeAnAppointment.setWeid(11);
    		imsWcyMakeAnAppointment.setBussinessid(1);
    		imsWcyMakeAnAppointment.setStoreid(53);
    		when(requestUtil.doPost(11, 1, 53, "/reserveCheck", null)).thenReturn("2");
              // Controller侧的RequestBody是javabean的场合
              // public String submit(@RequestBody ImsWcyMakeAnAppointment make,HttpServletRequest request){
              String jsonObject = JSONObject.fromObject(imsWcyMakeAnAppointment).toString();
              
    // Controller侧的RequestBody是Object[]的场合
              // public String XXXXXX(HttpServletRequest request,@RequestBody Object[] dto) throws IOException{
              Object[] dto = new String[] { "1", "1", "1" };
             String a = JSONArray.fromObject(dto).toString();
    		// parmがJSON
    		String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/openSesame/submit")
    				.contentType(MediaType.APPLICATION_JSON_VALUE).content(jsonObject)).andExpect(status().isOk())
    				.andReturn().getResponse().getContentAsString();
    		// result検証
    		Assert.assertEquals(1, 1);
    		System.out.println("哈哈哈" + responseString);
    	}
    }
    

      运行即可

    注※1 mock不好用的场合要确认被测试的类是否是@Service

    场合2:当你的Controller里面有用到下面的代码

      @RequestMapping(value = "/XXX", method = RequestMethod.POST)
    //  @RequestMapping("/mobilescreen/getfoodInfo")
      public String XXX(String itemCode, String syokujiCode, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONArray json = new JSONArray();
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        HttpSession session = request.getSession();
        Login userInfo = (Login) session.getAttribute("LOGIN_USER");
      }

    测试类要修正

    package com.cnc.mht.web.rest;
    
    import static org.mockito.Mockito.*;
    import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.mock.mockito.MockBean;
    import org.springframework.http.MediaType;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.mock.web.MockHttpServletRequest;
    import org.springframework.mock.web.MockHttpServletResponse;
    import org.springframework.mock.web.MockHttpSession;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.ResultActions;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    
    import com.cnc.mht.util.login.LoginUserInfoReform;
    
    @SpringBootTest
    @RunWith(SpringJUnit4ClassRunner.class)
    public class XXX_test {
    	@Autowired
    	private WebApplicationContext webApplicationContext;
    	private MockMvc mockMvc;
    	@Autowired
    	JdbcTemplate jdbctemplate = null;
    	private MockHttpServletRequest request;
    	@Autowired
    	MockHttpSession session;
    
    	@Before
    	public void setUp() throws Exception {
    		mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    	}
    
    	@Test
    	public void testComment1() throws Exception {
    		
    		
    		Login aa = new Login();
    		aa.setBussinessid(1);
    		session.setAttribute("LOGIN_USER", aa);
    		// parmがある
    		ResultActions responseString = mockMvc
    				.perform(MockMvcRequestBuilders.post("/mobilescreen/getfoodInfo")
    						.contentType(MediaType.APPLICATION_JSON_VALUE).session(session).param("itemCode", "11")
    						.param("syokujiCode", "1"));
    		System.out.print("aaa");
    
    	}
    
    }
    

    运行即可

  • 相关阅读:
    Domino+Qucikplace+Sametime构建企业办公平台图文攻略(一)
    GridPanel如果不设宽度,在IE下会变得很宽问题解决
    Domino+Qucikplace+Sametime构建企业办公平台图文攻略(二)
    extjs可视化开发工具
    JSON
    Domino的命名空间
    封装的ExtGrid 实现增、删、改、查等功能
    lotus 附件的存、 取 、删
    asp.net DateTime的使用
    SQL Server里面可能经常会用到的日期格式转换方法
  • 原文地址:https://www.cnblogs.com/killclock048/p/11630171.html
Copyright © 2020-2023  润新知