Springboot+junit单元测试
今天leader让我写好需求以后做一下单元测试,验证自己的代码逻辑是否正确。于是我很自然的就Alt+enter:
选中两个要测试的方法然后点击ok。生成的测试类如下:
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class MyPasswordEncoderTest {
@Autowired
private MyPasswordEncoder myPasswordEncoder;
@Test
public void encode() {
myPasswordEncoder.encode("1234567");
}
@Test
public void matches() {
}
}
然后在Test类中测试encode方法果断报错
很明显的这个NullPointerException异常应该就是@Autowired注入的实例不存在报的错误了。普通的测试类无法获取到bean,所以才会报空指针。于是我添加以下注释:
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.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) //运行器,指定用什么容器来运行
@SpringBootTest
public class MyPasswordEncoderTest {
@Autowired
private MyPasswordEncoder myPasswordEncoder;
@Test
public void encode() {
myPasswordEncoder.encode("1234567");
}
@Test
public void matches() {
}
}
然后跑出来就成功了。最简单的单元测试就这样完成了,但是如果要比较实际返回值和预期值怎么办呢?可以使用junit自带的assertXXX系列的比较方法,这里就举例assertEquals比较方法
//import static org.junit.Assert.assertEquals;
assertEquals("预期值","实际值"));
那么我们执行测试类不可能一直手点一个个测试类执行,那也太没有效率了,于是我们可以管理测试类,于是我在测试启动类中进行管理
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
//import org.springframework.test.context.junit4.SpringRunner;
//@RunWith(SpringRunner.class)
@RunWith(Suite.class) //将运行器指定为Suite
@SpringBootTest
@Suite.SuiteClasses({
// 按顺序执行填入的类
test1.class,
test2.class,
test3.class,
test4.class,
test5.class,
})
public class TestApplicationTests {
}
但是这样类的执行顺序是指定了,但是测试类中的测试方法的执行顺序却没有指定,那么怎么指定测试类中方法的顺序呢。
//采用下方的注解控制
@FixMethodOrder(value)
/*
MethodSorters.JVM
Leaves the test methods in the order returned by the JVM. Note that the order from the JVM
may vary from run to run (按照JVM得到的方法顺序,也就是代码中定义的方法顺序)
MethodSorters.DEFAULT(默认的顺序)
Sorts the test methods in a deterministic, but not predictable, order()
(以确定但不可预期的顺序执行)
MethodSorters.NAME_ASCENDING
Sorts the test methods by the method name, in lexicographic order, with Method.toString() used as a tiebreaker
(按方法名字母顺序执行)
*/