TDD与单元测试

一.TDD开发过程

        回顾TDD的开发过程,我们是在不断重复如下过程,直至需求完成。


二.TDD的收益


三.单元测试

        TDD是测试驱动开发,理所当然与单元测试有着密不可分的关系。

1.单元测试的目的:
a.拥抱变化
b.保证质量
c.好的单元测试可用来做为文档
d.也是一个重要的设计工具

2.单元测试过程:3A

3.测试类
a.命名:[被测试类]Test
b.测试类与被测试类在相同的包名下
c.一个被测试类对应一个测试类

4.测试目的和意图:
a.通过方法名表达测试目的和意图
b.Given-When-Then

5.测试方法:
a.案例一定要有验证
b.一个测试案例只测一个场景
c.案例独立不要互相依赖
d.测试方案中不要try/catch异常
e.测试方法中不要出现System.out或者Logger

6.测试用例三部曲:Arrange-Act-Assert

7.为什么要写单测:
a.快速反馈
b.自信
c.进度可视化
d.明确目标
e.聚焦
f.说明书
g.回归测试
h.拆分功能
i.可测试
j.质量保证
k.设计

8.Junit Cheat Sheet
a.Annotations
@Test
b.Assertions
assertEquals
assertTrue/assertFalse
assertNull/assertNotNull
assertSame/assertNotSame:比较引用
fail/pass

9.单元测试
Adv.Assertion
a.约束验证:assertThat([actual],[matcher])
is(true)
not(nullValue())
either(containsTring("a")).or(containsString("b"))
anyOf(containsString("a"),containsString("b"))
hasItem(orderl)
b.第三方/自定义断言
c.每个测试案列
准备:@Before
清理:@After
d.每个测试类
准备:BeforeClass
清理:AfterClass

10.单元测试样例
public class StringParserTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public voi should_throw_exception_when_given_character() {
   expectedException.expect(IllegalArgumentException.class);
   expectedException.expectMessage("Argument should be int");
  
   new StringParser().parseAndSum("a");
}

@Test(expected = IllegalArgumentException.class)
public void should_throw_exception_when_given_null() {
   new StringParser().parseAndSum(null);  
}
}

Timeout
public class SquareTest {
    @Test(timeout = 1000)
    public void squareRoot() {
        calculator.squareRoot(4);
        assertEquals(2, claculator.getResult());
    }
}

参数化运行Junit
@RunWith(Parameterized.class)
public class EmailUtilsParameterizedTest {
    @Parameterized.Parameters
    public static Collection<Object[]> data() {
   
        return Arrays.asList


@RunWith(Theories.class)
public class EmailUtilsTheoryTest {
@DataPoints
public static TestData[] ARRAYS = new

@Theory

11.Test Data
a.Data Mother
b.Test data organization Builder

猜你喜欢

转载自bijian1013.iteye.com/blog/2118848