单元测试

对于简单易懂的小项目而言,可以不适用单元测试对平时开发没有什么影响,但是对于大型项目,单纯的依赖 “手点功能测试”, 那简直就是灾难,SpringBoot2.X 如何测试?

1、引入相关依赖

<!--springboot程序测试依赖,如果是自动创建项目默认添加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <!--当前依赖只参与测试-->
</dependency>

2、使用

Junit相信很多人都相当的熟悉了,SpringBoot 2.X 默认使用Junit4

@RunWith(SpringRunner.class)   
@SpringBootTest(classes={Application.class})
public class ApplicationTests {
@Test
public void testOne(){
System.out.println("test");
}

@Test
public void testTwo(){
TestCase.assertEquals(1, 1);//推荐
}

@Before
public void testBefore(){
System.out.println("before");
}

@After
public void testAfter(){
System.out.println("after");
}
}

当然也可以注入要测试的组件

@RunWith(SpringRunner.class)
@SpringBootTest
public class HellowordApplicationTests {
@Autowired
Person person;
@Test
public void contextLoads() {
System.out.println(person);
}
}

Junit基本注解介绍

@BeforeClass 在所有测试方法前执行一次,一般在其中写上整体初始化的代码

@AfterClass 在所有测试方法后执行一次,一般在其中写上销毁和释放资源的代码

@Before 在每个测试方法前执行,一般用来初始化方法(比如我们在测试别的方法时,类中与其他测试方法共享的值已经被改变,为了保证测试结果的有效性,我们会在@Before注解的方法中重置数据)

@After 在每个测试方法后执行,在方法执行完成后要做的事情

@Test(timeout = 1000) 测试方法执行超过1000毫秒后算超时,测试将失败

@Test(expected = Exception.class) 测试方法期望得到的异常类,如果方法执行没有抛出指定的异常,则测试失败

@Ignore(“not ready yet”) 执行测试时将忽略掉此方法,如果用于修饰类,则忽略整个类

@Test 编写一般测试用例

@RunWith 在JUnit中有很多个Runner,他们负责调用你的测试代码,每一个Runner都有各自的特殊功能,你要根据需要选择不同的Runner来运行你的测试代码。

热部署

对于boot项目可以加入以下热部署依赖,修改完项目之后不用每次重启项目

<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

DEA进行SpringBoot热部署失败

出现这种情况,并不是热部署配置问题,其根本原因是因为Intellij IEDA默认情况下不会自动编译,需要对IDEA进行自动编译的设置如下:

1) “File” -> “Settings” -> “Build,Execution,Deplyment” -> “Compiler”,选中打勾 “Build project automatically” 。
2)组合键:“Shift+Ctrl+Alt+/” ,选择 “Registry” ,选中打勾 “.running” 。

 

交流公众号 java一号