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

运行即可

Javaspring+mybit+maven中实现Junit测试类的更多相关文章

  1. Javaspring+mybit+maven中实现定时任务

    背景:在Javaspring中,定时的启动某一个任务时,使用@Scheduled来实现 Javaspring工程创建好之后,直接创建下面的class文件即可.具体的用法可参照 https://www. ...

  2. Spring4.2.3+Hibernate4.3.11整合( IntelliJ maven项目)(使用Annotation注解)(Junit测试类)

    1. 在IntelliJ中新建maven项目 给出一个建好的示例 2. 在pom.xml中配置依赖 包括: spring-context spring-orm hibernate-core mysql ...

  3. 在Eclipse中生成接口的JUnit测试类

    在Spring相关应用中,我们经常使用“接口” + “实现类” 的形式,为了方便,使用Eclipse自动生成Junit测试类. 1. 类名-new-Other-java-Junit-Junit Tes ...

  4. eclipse使用maven打包时去掉测试类

    eclipse使用maven打包时去掉测试类 在pom.xml文件中增加如下配置: <plugin> <groupId>org.apache.maven.plugins< ...

  5. 15.junit测试类使用及注解

    1.junit简介 JUnit是一个Java语言的单元测试框架,可以大大缩短你的测试时间和准确度.多数Java的开发环境都已经集成了JUnit作为单元测试的工具. 2.实现junitDemo示例 2. ...

  6. maven编译的时候排除junit测试类

    maven项目中使用junit进行单元测试,在进行编译的时候,可以通过2种方式排除test测试类的编译. 有2种方式 : 使用命令的时候带上参数 mvn install -Dmaven.test.sk ...

  7. Junit测试类中如何调用Http通信

    在使用Junit做测试的时候,有时候需要调用Http通信,无论是request还是response或者是session会话,那么在测试类里该如何调用呢,其实很简单,spring给我们提供了三个类 or ...

  8. java中使用junit测试

    最初写代码只要功能走通就不管了,然后如果出了什么问题再去修改,这是因为没做测试的工作.测试其实很简单. 1.准备 当前使用idea编写代码,用maven构建工程,使用maven的test功能来进行批量 ...

  9. 高并发秒杀系统--junit测试类与SpringIoc容器的整合

    1.原理是在Junit启动时加载SpringIoC容器 2.SpringIoC容器要根据Spring的配置文件加载 [示例代码] package org.azcode.dao; import org. ...

随机推荐

  1. mysql 查询今天,昨天,上个月sql语句

    今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天Select * FROM 表名 Where TO_DAYS( NOW( ) ...

  2. 学习Microsoft Visio(1)

    基础篇 一.认识Visio 1.Visio是什么 Visio最初属于Visio公司,该公司成立于1990年9月.1992年,公司更名为Shapeware.同年11月,它发布了他们公司的第一个产品:Vi ...

  3. SOLOR介绍

    https://www.cnblogs.com/ki16/p/11209508.html

  4. 第三章 - SQL基础及元数据获取

    SQL的介绍 SQL的定义:结构化查询语句 SQL的作用:对库和表进行操作 SQL的常用分类 DDL 数据定义语言(Data Definition Language) DCL 数据控制语言(Data ...

  5. Redis的订阅、事务、持久化

    1.Redius的订阅: 运用关键字subscribe订阅: 关键字publish发布: 发布后,订阅的页面才会出现发布的内容. 2.Redis事务: Redis事务与mysql的事务不同,mysql ...

  6. Lightning Web Components 开发指南(二)

    Lightning Web Components 是自定义元素使用html 以及现代javascript进行构建. Lightning Web Components UI 框架使用web compon ...

  7. [RN] React Native 下列表 FlatList 和 SectionList

    1.FlatList FlatList组件用于显示一个垂直的滚动列表,其中的元素之间结构近似而仅数据不同. FlatList更适于长列表数据,且元素个数可以增删.和ScrollView不同的是,Fla ...

  8. 解决js加减乘除精度问题

    // 加法 const accAdd = (arg1, arg2) => {     var r1, r2, m;     try {         r1 = arg1.toString(). ...

  9. javascript使用history api防止|阻止页面后退

    奇葩需求啥时候都会有,最近有个需求是不允许浏览器回退,但是所有页面都是超链接跳转,于是乎脑壳没转弯就回答了做不到,结果尼玛被打脸了,这打脸的声音太响,终于静下心来看了下history api. 先上代 ...

  10. shell 修改文件所有者

    chown   用户名   文件名  -R