什么是单元测测试

定义:单元测试是对软件或者程序的基本(最小)组成单元的测试
对象:方法、类
特点:
-可重复执行;
-执行速度快;
-独立无依赖;
-结果不改变。


为什么要写单元测试

-使我们更了解需求;
-使重构更容易;
-更早了解程序的问题;
-快速验证;
-目标明确。


测试分类

单元测试->集成测试->端到端测试

各测试占比


Junit介绍

Junit例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.junit.*;
import static org.junit.Assert.fail;

public class ClassNameTest {
@BeforeClass //公开表态无返回值
public static void beforeClass() throws Exception{
//每次测试类执行前执行一次,主要用来初使化公共资源等
}
@AfterClass //公开表态无返回值
public static void afterClass() throws Exception{
//每次测试类执行完成后执行一次,主要用来释放资源或清理工作
}
@Before
public void setup() throws Exception {
//每个测试案例执行前都会执行一次
}
@After
public void teardown() throws Exception {
//每个测试案例执行完成后都会执行一次
}
@Test
public void testMethodName_give_…_when_…_then_…() {
fail("失败");
}
}

常用注解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Ignore 
该注解标记的测试方法在测试中会被忽略
@Test
@Test(expected=xxxException.class) 断言该方法会抛出异常
@Test(timeout=1000) 执行时间超过设置的值该案例会失败
@RunWith
@RunWith(Suite.class) 测试集运行器配合使用测试集功能
@RunWith(JUnit4.class) 默认运行器
@RunWith(Parameterized.class) 参数化运行器
@RunWith(Suite.class)
@Suite.SuiteClasses({CalculatorTest.class,SquareTest.class})
@Rule
public class ExpectedExceptionsTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void verifiesTypeAndMessage() {
thrown.expect(RuntimeException.class);
thrown.expectMessage("Runtime exception occurred");
throw new RuntimeException("Runtime exception occurred");
}
}

参数化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@RunWith(Parameterized.class)
public class PrimeFactorTest {
private PrimeFactor primeFactor;
private int input;
private List<Integer> expected;
//构造函数
public PrimeFactorTest(int input, List<Integer> expected) {
this.input = input;
this.expected = expected;
}
@Parameterized.Parameters
public static Collection init() {
return Arrays.asList(new Object[][]{
{18, Arrays.asList(2, 3, 3)}
});
}
@Test
public void testFactor_when_input_18_then_must_return_2_3_3() {
Assert.assertEquals(expected, primeFactor.factor(input));
}
}

断言:
常用的断言方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
assertEquals(a, b)    测试a是否等于b(a和b是原始类型数值(primitive value)或者必须为实现比较而具有equal方法)
assertFalse(a) 测试a是否为false(假),a是一个Boolean数值。

assertTrue(a) 测试a是否为true(真),a是一个Boolean数值

assertNotNull(a) 测试a是否非空,a是一个对象或者null。

assertNull(a) 测试a是否为null,a是一个对象或者null。

assertNotSame(a, b) 测试a和b是否没有都引用同一个对象。

assertSame(a, b) 测试a和b是否都引用同一个对象。

fail(string) Fail让测试失败,并给出指定信息。

assertThat(expected, Matcher) 通过Matcher断言

Hamcrest :greaterThan,greaterThanOrEqualTo,lessThan,anything,anyOf,containsString

最后更新: 2019年10月15日 11:59

原始链接: http://leiii33.github.io/2019/10/12/Java单元测试/