【SpringBoot】Junit单元测试简单入门

talk is cheap, show me the code.

SpringBoot 测试依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

基础使用

  • 不需依赖 Spring 环境
public class TestAES {

    @Test
    public void encrypt() {
        String token = "yJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9";
        AES aes = new AES();
        Assert.assertEquals(token, aes.decode(aes.encode(token)));
    }
    
}
  • 依赖 Spring 环境
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestHello {

	@Autowire
	private HelloService helloService;
	
    @Test
    public void hello() {
        Assert.assertEquals("hello tanpeng", helloServic.sayHi());
    }
    
}

注解说明

  • 注解列表
    • @RunWith 标识为JUnit的运行环境
    • @SpringBootTest 获取启动类、加载配置,确定装载Spring Boot
    • @Test 声明需要测试的方法
    • @BeforeClass 针对所有测试,只执行一次,且必须为static void
    • @AfterClass 针对所有测试,只执行一次,且必须为static void
    • @Before 每个测试方法前都会执行的方法
    • @After 每个测试方法前都会执行的方法
    • @Ignore 忽略方法
  • 超时测试
    • @Test(timeout = 1000) Test设置timeout属性即可,时间单位为毫秒

断言测试

断言测试也就是期望值测试,是单元测试的核心也就是决定测试结果的表达式

Assert对象中的断言方法

  • Assert.assertEquals 对比两个值相等
  • Assert.assertNotEquals 对比两个值不相等
  • Assert.assertSame 对比两个对象的引用相等
  • Assert.assertArrayEquals 对比两个数组相等
  • Assert.assertTrue 验证返回是否为真
  • Assert.assertFlase 验证返回是否为假
  • Assert.assertNull 验证null
  • Assert.assertNotNull 验证非null
发布了109 篇原创文章 · 获赞 46 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/AV_woaijava/article/details/105080137