TDD之Hamcrest系列1---數值相關匹配器1?

Hamcrest其實不能做單元測試,做單元測試的框架是Junit。

Hamcrest是個匹配器,可以讓我們更方便,更高效的寫出我們預期的單元測試

Junit是部車,Hamcrest就是一個強大的變速箱嘍

本文就來分享一下Hamcrest中與字串匹配相關的匹配器:

closeTo

greaterThan

lessThan

工具/原料

IntelliJ IDEA

Hamcrest

junit

方法/步驟

需要的jar:

junit-4.11.jar

hamcrest-core-1.3.jar

hamcrest-library-1.3.jar//這個Jar也是必需的哦。裡面有不少有用的方法

jar的版本可以根據自己的需要進行調整

匹配器closeTo的使用

先來個失敗的UT:

場景1:20.6>20.5

Code:

package tdd;

import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;

import static org.hamcrest.Matchers.closeTo;

/**

* Created by MyWorld on 2016/3/18.

*/

public class HamcrestMatch {

@Test

public void commonMatch() {

assertThat(20.6, closeTo(20.0, 0.5));

}

}

TDD之Hamcrest系列1---數值相關匹配器1

匹配器closeTo限制了一個區間,我們測試這個區間的下限

變紅的 場景2:19.4<19.5

Code:

assertThat(19.4, closeTo(20.0, 0.5));

TDD之Hamcrest系列1---數值相關匹配器1

變綠

因為actual的值在[20.0-0.5,20.0+0.5]

Code:

assertThat(20.5, closeTo(20.0, 0.5));

assertThat(20.4, closeTo(20.0, 0.5));

assertThat(19.6, closeTo(20.0, 0.5));

assertThat(19.5, closeTo(20.0, 0.5));

TDD之Hamcrest系列1---數值相關匹配器1

匹配器greaterThan的使用

變紅:19.4==19.4

Code:

assertThat(19.4, greaterThan(19.4));

TDD之Hamcrest系列1---數值相關匹配器1

變綠:只要比19.4大就可以了

Code:

assertThat(19.5, greaterThan(19.4));

TDD之Hamcrest系列1---數值相關匹配器1

匹配器lessThan的使用

變紅:19.4==19.4,要變綠actual的值需要小於19.4即可

Code:

assertThat(19.4, lessThan(19.4));

TDD之Hamcrest系列1---數值相關匹配器1

變綠:19.3<19.4

Code:

assertThat(19.3, lessThan(19.4));

TDD之Hamcrest系列1---數值相關匹配器1

相關問題答案

Have any Question?

Let us answer it!