springboot(5)——整合单元测试

概述

对于简单易懂的小项目而言,可以不适用单元测试对平时开发没有什么影响,但是对于大型项目,单纯的依赖 “手点功能测试”, 那简直就是灾难,好了,说道这里,应该明白测试的一个重要性了,,,接下来,我们正式进入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来运行你的测试代码。

公众号 java一号 更多java实战项目资料、技术干活。更重要的是小猿愿成为你编程路上的一个朋友!

文章首发地址: www.javayihao.top

首发公众号: java一号

猜你喜欢

转载自www.cnblogs.com/javayihao/p/11807051.html