【Springboot学习】在Springboot中使用Junit进行测试
前言
一般在测试Java用例时使用的都是main方法,这样就需要我们不断地修改main方法,导致测试代码通常无法保留或者不规范,因此Java提供了Junit进行更为优雅的白盒测试方式。
步骤
- 定义一个测试类(测试用例)
- 测试类名: 被测试类名+Test CalculatorTest
- 包名: xxx.xxx.xx.test com.tnxts.test
import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class testCalculate { }
- 定义测试方法: 可以独立运行
- 方法名: test测试的方法名 testAdd()
- 返回值: void
- 参数列表: 空参
import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class testCalculate { @Test public void testAdd(){ Calculate c = new Calculate(); int resultA = c.add(1,2); int resultB = c.sub(1,2); System.out.println(resultA); System.out.println(resultB); } }
- 使用断言判断正确与否
import org.junit.Assert; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class testCalculate { @Test public void testAdd(){ Calculate c = new Calculate(); int resultA = c.add(1,2); int resultB = c.sub(1,2); Assert.assertEquals(3,resultA); } } - 结果(测试成功)

@Before与@After
- 使用@Before注解的方法在测试方法执行前执行,可以用作测试方法的初始化,如资源的申请
- 使用@Before注解的方法在测试方法执行后执行,可以用作资源的回收
测试
测试代码
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class testCalculate {
@Before
public void init()
{
System.out.println("before...");
}
@Test
public void test(){
System.out.println("test...");
}
@After
public void close()
{
System.out.println("After...");
}
}
测试结果

注意
即使test方法出现了异常,使用after和before仍然会正常执行。

浙公网安备 33010602011771号