SpringBoot之junit
juint
1. 依赖
修改pom.xml 增加依赖,一般Spring Boot项目有引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.增加测试类基类(避免每个类都需要注解)
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class SpringbootdemoApplicationTests {
@Before
public void init() {
System.out.println("开始测试-----------------");
}
@After
public void after() {
System.out.println("测试结束-----------------");
}
}
3.测试类
public class TestServices extends SpringbootdemoApplicationTests {
@Autowired
Service service;
@Test
//回滚数据操作
@Transactional
public void testDelete() {
service.deleteById("111111");
}
4.打包测试
@Suite.SuiteClasses({TestServices.class,TestServices2.class})
//@Ignore("not ready yet")
@RunWith(Suite.class)
@Suite.SuiteClasses({TestServices.class,TestServices2.class})
public class TestSuits {
}
5.忽略方法
@Ignore("not ready yet")
断言
待补充
常见问题解决
私有方法测试
private Double format(Double fileSize){
Double size = fileSize;
size = size / 1024 / 1024;
size = (int)(size.doubleValue() * 10 + 0.5) / 10.0;
return size;
}
@Test
public void testFormat(){
ClientDownloadAction action = new ClientDownloadAction();
double size = 3732930;
Class class1 = action.getClass();
try {
Method format = class1.getDeclaredMethod("format", Double.class);
format.setAccessible(true);//设为可见
Double result = (Double)format.invoke(action, size);
Double expect = 3.6;
Assert.assertEquals(expect, result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
controller 层测试
待补充
数据回滚
websocket导致测试类启动失败
加载需要加载servlet容器,根据
参考4中的解决方法
修改类上面的注解
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
maven打包时去除 test

SpringBoot单元测试详解:依赖、基类、断言及问题解决
本文介绍了SpringBoot中使用JUnit进行单元测试的实践,包括添加测试依赖、创建测试基类、编写测试类、打包测试、忽略测试方法以及断言的使用。同时,针对私有方法测试、Controller层测试、数据回滚和WebSocket测试问题给出了解决方案。此外,还提到了在maven打包时排除测试代码的方法。
2582

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



