springboot编写单元测试
1. pom:需要引⼊的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2. ideal添加插件:Junit Generator,使⽤快捷键:打开代码,选择要创建test的类,ctrl+shift+t,⾃动⽣成的代码默认在test.java下
(路径可改,在Junit Generator下修改)
3. 添加测试配置,1中注解中的l,的resource,新建
配置内容:
spring:
datasource:
url: jdbc:mysql://localhost:3306/my_sys?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&allowMultiQueries=tr ue
username: root
password: root
jpa:
show-sql: true
hibernate:
ddl-auto: update
server:
port: 8183
根据需要添加,⽐如redis等
4. ⾸先在test.java下创建BaseTest,测试基类,⽬的在于省去每个test写注解,和相同的⽅法
kj.passport;
import org.junit.runner.RunWith;
import org.st.context.SpringBootTest;
import st.context.TestPropertySource;
import st.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@TestPropertySource(locations = {"l"})
@SpringBootTest
public abstract class BaseTest {
}
可以根据情况添加默认查询⽅法,⽐如:权限查询,⽤户查询等
5、选中要test的类(code中的),ctrl+shift+t,填⼊基类,勾选需要测试的⽅法。如:
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.t.WebApplicationContext;
import static Is.is;
import static org.junit.Assert.*;
public class AuthControllerTest extends BaseTest {
@Autowired
private WebApplicationContext context;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void register() {
System.out.println("");
Assert.assertThat("aaa", is("aab"));
}
}
右键运⾏即可。断⾔语句 is() 需要alt+enter引⼊import static ;,关于断⾔语句见附录1,关于注解见附录2。control层测试,使⽤MockMVC
1. 使⽤mockmvc测试控制层代码
kj.passport.dto.UserDetails;
ity.User;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.st.web.client.TestRestTemplate;
import ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import k.web.MockHttpSession;
import st.web.servlet.MockMvc;
import st.quest.MockMvcRequestBuilders;
import st.sult.MockMvcResultHandlers;
import st.sult.MockMvcResultMatchers;
import st.web.servlet.setup.MockMvcBuilders;
import org.t.WebApplicationContext;
import java.util.List;
import static Is.is;
import static org.junit.Assert.*;
public class AuthControllerTest extends BaseTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(context).build();// 使⽤WebApplicationContext初始化mockMVC
}
@After
public void tearDown() throws Exception {
}
@Test
public void register() throws Exception {
String json = "{'admin':'admin'}";
Assert.assertThat(json, is("{'admin':'admin'}"));// 可作为数据检查
//发送post请求
mvc.perform(MockMvcRequestBuilders.post("register")
.accept(MediaType.APPLICATION_JSON_UTF8)
.Bytes())
/*.session(new MockHttpSession())*/
).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
//Spring Boot Web 测试带返回结果
ParameterizedTypeReference<List<UserDetails>> type = new ParameterizedTypeReference<List<UserDetails>>() {};        ResponseEntity<List<UserDetails>> result = hange("/get", HttpMethod.GET, null, type);
Assert.Body().get(0).getUsername(), NullValue());
}
}
关于Mock详情见www.importnew/21540.html
参数化测试
//1.更改默认的测试运⾏器为RunWith(Parameterized.class)
@RunWith(Parameterized.class)
equals不等于public class ParameterTest {
// 2.声明变量存放预期值和测试数据
private String firstName;
private String lastName;
//3.声明⼀个返回值为Collection的公共静态⽅法,并使⽤@Parameters进⾏修饰    @Parameterized.Parameters //
public static List<Object[]> param() {
// 这⾥我给出两个测试⽤例
return Arrays.asList(new Object[][]{{"Mike", "Black"}, {"Cilcln", "Smith"}});
}
//4.为测试类声明⼀个带有参数的公共构造函数,并在其中为之声明变量赋值
public ParameterTest(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// 5. 进⾏测试,发现它会将所有的测试⽤例测试⼀遍
@Test
public void test() {
String name = firstName + " " + lastName;
assertThat("Mike Black", is(name));
}
}
超时测试
⽅法前加注解@Test(timeout = 1000)
异常测试
⽅法前加注解@Test(expected = NullPointerException.class)
套件测试
public class TaskOneTest {
@Test
public void test() {
System.out.println("Task one do.");
}
}
public class TaskTwoTest {
@Test
public void test() {
System.out.println("Task two do.");
}
}
public class TaskThreeTest {
@Test
public void test() {
System.out.println("Task Three.");
}
}
@RunWith(Suite.class) // 1. 更改测试运⾏⽅式为 Suite
// 2. 将测试类传⼊进来
@Suite.SuiteClasses({TaskOneTest.class, TaskTwoTest.class, TaskThreeTest.class}) public class SuitTest {
/**
* 测试套件的⼊⼝类只是组织测试类⼀起进⾏测试,⽆任何测试⽅法,
*/
}
事务控制
在@Test注解下添加@Transactional
使⽤的数据库要⽀持事务(如:mysql的innodb)
关闭回滚加注解@Rollback(false)
附录:
1、 Hamcrest 下断⾔语句

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。