目录
在junit4.12中,Assert过时,被TestCase取代
extends AbstractTransactionalJUnit4SpringContextTests 需要配置事务
在junit4.12中,Assert过时,被TestCase取代
import junit.framework.Assert;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import stu.bestcxx.sshmaven.sshmaventest.model.PersonModel;
@SuppressWarnings("deprecation")
@DirtiesContext
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/applicationContext.xml"})
public class PersonServiceTest {
@Autowired
private PersonService personService;
@Test
public void testAddPerson(){
PersonModel person=new PersonModel();
person.setUserName("Jecket");
person.setUserPassword(Math.random()*100+"");
//断言:期待结果,实际结果 是否相等,下面 true 是期待结果,后面是条件语句,二者不等程序会报异常,可以自定义异常的提示语,true前可设置该参数
Assert.assertEquals(true,personService.addPerson(person));
TestCase.assertEquals(true,personService.addPerson(person));//可以增加提示信息TestCase.assertEquals("期待结果为true,实际结果(条件语句)为false,报错提示本信息",true,条件语句)
}
}
Spring测试
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.bestcxx.stu.springmvc.model.UserModel;
import com.bestcxx.stu.springmvc.service.UserModelService;
@DirtiesContext
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/springmvc-servlet.xml"})
//@TransactionConfiguration(transactionManager = "defaultTransactionManager",defaultRollback=false)//事务管理
@Rollback(true)
public class UserModelServiceImplTest extends AbstractTransactionalJUnit4SpringContextTests{
Spring Boot 测试
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
需要借助启动类加载配置文件
import com.bestcxx.stu.simpled.starter.StarterApplication;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @Title: 包含 SpringBoot Test 模块相关配置
* @Description: 基础 Test
* @Analysis:
* @Copyright: Copyright(c)2021
* @Company: bestcxx
* @Author: jie.wu
* @Version: v1.0
* @Date:2022-11-01 09:12
* @Updatedby:
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StarterApplication.class)//StarterApplication是启动类
public class BaseTest {
}
TestCase-try-Catch
@Test
public void test(){
int id=10000;
EnterpriseInfo e=eService.getById(id);
e.setUpdateUser(10000);//最后更新用户
try {
eService.update(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
TestCase.fail("保存失败");
}
}
Mock
validate 的 maven依赖
<!-- validation 校验 开始 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<!-- validation 校验 结束 -->
Mock 测试举例
package com.bestcxx.stu.springmvc.controller;
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.annotation.DirtiesContext;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringRunner;
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.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@DirtiesContext
@RunWith(SpringRunner.class) //@RunWith(SpringJUnit4ClassRunner.class) 也是可以的
@WebAppConfiguration //单元测试的时候真实的开启一个web服务
@ContextConfiguration(locations={"classpath:spring/springmvc-servlet.xml"})
//@TransactionConfiguration(transactionManager = "defaultTransactionManager",defaultRollback=false)//事务管理
@Rollback(true)
public class ParameterControllerTest extends AbstractTransactionalJUnit4SpringContextTests{
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //构造MockMvc
}
@Test
public void testMock() throws Exception{
MultiValueMap<String, String> params=new LinkedMultiValueMap<String,String>();
params.add("recordTitle","测试标题");
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/recordinfo/add") // 请求的url,请求的方法是post
.contentType(MediaType.APPLICATION_JSON) // 数据的格式
//.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) // 数据的格式
.params(params)
//.param("recordTitle","测试标题" ) // 增加参数
).andExpect(MockMvcResultMatchers.status().isOk()) // 返回的状态是200
.andDo(MockMvcResultHandlers.print()) // 打印出请求和相应的内容
.andReturn(); // 将相应的数据转换为字符串
System.out.println("--------返回的json = " + mvcResult.getResponse().getContentAsString());
}
}
Spring boot 举例
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.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.UnsupportedEncodingException;
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.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringRunner;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import junit.framework.TestCase;
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@Rollback(true) //单元测试配置数据库默认会事务会退 此时强制事务提交
public class ApplyRecordControllerTest extends AbstractTransactionalJUnit4SpringContextTests{
private MockMvc mockMvc;
@Autowired
protected WebApplicationContext wac;
// 该方法在每个方法执行之前都会执行一遍
@Before
public void setUp() throws Exception {
//mockMvc = MockMvcBuilders.standaloneSetup(new NameController()).build();
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc对象
}
@Test
public void test1() throws UnsupportedEncodingException, Exception {
String responseString = mockMvc.perform(post("/a/b") // 请求的url,请求的方法是post
.contentType(MediaType.APPLICATION_JSON) // 数据的格式
.param("a","111" ) // 参数
.param("b", "222")//参数
).andExpect(status().isOk()) // 返回的状态是200
.andDo(print()) // 打印出请求和相应的内容
.andReturn().getResponse().getContentAsString(); // 将相应的数据转换为字符串
System.out.println("--------返回的json = " + responseString);
}
@Test
public void test2() throws UnsupportedEncodingException, Exception {
String responseString = mockMvc.perform(post("/c/d") // 请求的url,请求的方法是post
.contentType(MediaType.APPLICATION_JSON) // 数据的格式
.param("a","111" ) // 参数
.param("c","222" ) // 参数
).andExpect(status().isOk()) // 返回的状态是200
.andDo(print()) // 打印出请求和相应的内容
.andReturn().getResponse().getContentAsString(); // 将相应的数据转换为字符串
System.out.println("--------返回的json = " + responseString);
}
@Test
public void test3() throws UnsupportedEncodingException, Exception {
MvcResult mvcResult = mockMvc.perform(get("/a/1000") // 请求的url,请求的方法是post
.contentType(MediaType.APPLICATION_JSON) // 数据的格式
).andExpect(status().isOk())// 返回的状态是200
//.andDo(print()) // 打印出请求和相应的内容
.andReturn()
; // 将相应的数据转换为字符串
TestCase.assertEquals("/a/b/c", mvcResult.getModelAndView().getViewName());//返回页面是否符合预期
}
}
extends AbstractTransactionalJUnit4SpringContextTests 需要配置事务
下面是一个典型的测试方法头部注释,继承 AbstractTransactionalJUnit4SpringContextTests 会使程序报异常
@DirtiesContext
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
//@TransactionConfiguration(transactionManager = "defaultTransactionManager",defaultRollback=false)//事务管理
@Rollback(true)
public class TestTableOneMapperTest extends AbstractTransactionalJUnit4SpringContextTests{
/* public class TestTableOneMapperTest extends AbstractTransactionalJUnit4SpringContextTests{
*/
异常内容主要信息为
java.lang.IllegalStateException: Failed to retrieve PlatformTransactionManager for @Transactional
原因是没有配置事务。
JUnit与Spring测试实践
本文介绍了JUnit 4.12中Assert的使用及被替换情况,并通过多个示例详细展示了如何进行Spring和Spring Boot项目的单元测试,包括配置、依赖管理和Mock测试等。
2268

被折叠的 条评论
为什么被折叠?



