1.前言
一般我们写好了一个接口,并且实现后,我们要写对应的测试用例,因为公司这边对我们写的代码要达到一定的测试覆盖率,也就是检测我们的代码质量
需要了解的东西:Junit4
Spring-test,@RunWith和 SpringJUnit4ClassRunner
测试覆盖率
GitLab CI/CD
SonarQube 可以在日常开发中检测代码质量
2.测试Junit
不用注解,Spring+junit4 实现注解测试
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="java.util.Date" id="date"/>
</beans>
不用注解
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Date;
/**
* Created by lanxinghua on 2018/7/12.
*/
public class DataTest {
@Test
public void myTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Date date = (Date) context.getBean("date");
System.out.println(date.getTime());
}
}
七月 12, 2018 2:26:12 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
1531376772803
Spring+junit4 实现注解测试
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
FixMethodOrder指定测试方法的执行顺序
我们在写JUnit测试用例时,有时候需要按照定义顺序执行我们的单元测试方法,比如如在测试数据库相关的用例时候要按照测试插入、查询、删除的顺序测试。如果不按照这个顺序测试可能会出现问题,比如删除方法在前面执行,后面的方法就都不能通过测试,因为数据已经被清空了。而JUnit测试时默认的顺序是随机的。所以这时就需要有办法要求JUnit在执行测试方法时按照我们指定的顺序来执行。
JUnit是通过@FixMethodOrder注解(annotation)来控制测试方法的执行顺序的。@FixMethodOrder注解的参数是org.junit.runners.MethodSorters对象,在枚举类org.junit.runners.MethodSorters中定义了如下三种顺序类型:
- MethodSorters.JVM:按照JVM得到的方法顺序,也就是代码中定义的方法顺序
- MethodSorters.DEFAULT(默认的顺序):按照JVM得到的方法顺序,也就是代码中定义的方法顺序
- MethodSorters.NAME_ASCENDING:按方法名字母顺序执行
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
* Created by lanxinghua on 2018/7/12.
*/
@FixMethodOrder(MethodSorters.JVM)
public class OrderTest {
@Test
public void bTest(){
System.out.println("b Test");
}
@Test
public void aTest(){
System.out.println("a Test");
}
@Test
public void cTest(){
System.out.println("c Test");
}
}
其他的情况自己去玩一下吧!!!!
Gitlab CI/CD
在使用Gitlab的公司,使用Gitlab提供的各项功能,实现公司代码的管理、自动化编译同步等,具有非常明显的优势。通Jenkins相比,使用CI/CD可以个性化定制自己的编译内容,并触发执行,无需实现设置crontab配置。