单元测试
端到端测试(非单元测试)
将系统作为一个整体来测试
运行速度慢
无法隔离与定位问题
什么不是单元测试: 网络 文件IO 数据库
临时单元测试: 打印语句 日志 调试器
格式
//Given
...
//When
...
//Then
单元测试DEMO
main.FizzBuzz.java
1 package main; 2 3 /** 4 * Created by SHINE on 7/20/2017. 5 */ 6 public class FizzBuzz { 7 public static String fizzBuzz(int number) { 8 return "Fizz"; 9 } 10 }
test.FizzBuzzTest.java
1 package test; 2 3 import main.FizzBuzz; 4 import org.hamcrest.core.IsEqual; 5 import org.junit.Test; 6 7 import static org.hamcrest.MatcherAssert.assertThat; 8 import static org.hamcrest.core.IsEqual.equalTo; 9 10 11 /** 12 * Created by SHINE on 7/20/2017. 13 */ 14 public class FizzBuzzTest { 15 @Test 16 public void should_return_Fizz_when_number_is_divisible_by_3() throws Exception{ 17 //Given 18 int number = 3; 19 //When 20 String result = FizzBuzz.fizzBuzz(number); 21 //Then 22 assertThat(result, equalTo("Fizz")); 23 } 24 25 @Test 26 public void should_return_Buzz_when_number_is_divisible_by_5() throws Exception { 27 //Given 28 int number = 5; 29 //When 30 String result = FizzBuzz.fizzBuzz(number); 31 //Then 32 assertThat(result, equalTo("Buzz")); 33 34 } 35 36 @Test 37 public void should_return_FizzBuzz_when_number_is_divisible_by_15() throws Exception { 38 //Given 39 int number = 15; 40 //When 41 String result = FizzBuzz.fizzBuzz(number); 42 //Then 43 assertThat(result, equalTo("FizzBuzz")); 44 } 45 46 @Test 47 public void should_return_itself_when_number_is_undivisible_by_3_5() throws Exception { 48 //Given 49 int number = 1; 50 //When 51 String result = FizzBuzz.fizzBuzz(number); 52 //Then 53 assertThat(result, equalTo("1")); 54 } 55 }