首页 技术 正文
技术 2022年11月9日
0 收藏 442 点赞 3,357 浏览 6572 个字

在一个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");}}

运行即可

上一篇: MySQL之表关系
下一篇: Redis专栏
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295