編寫測試代碼時,我們總會有我們對被測方法自己預期的值,以及調用被測方法后返回的真實執行后的值。需要斷言這兩個值是否相等、拋出異常、hash碼等等情況。。。
這里博主主要介紹一下簡單的斷言和mock。如果已經對junit測試有過相對了解的,請略過這篇文章。
下面是我准備的節點類:
1 package demo; 2 3 /** 4 * @author Lcc 5 * 6 */ 7 public class Node { 8 private int value; 9 10 public Node(int value) { 11 this.value = value; 12 } 13 14 public String toString() { 15 return "它本來的值是:" + value; 16 } 17 18 public int getValue() { 19 return value; 20 } 21 22 public void setValue(int value) { 23 this.value = value; 24 } 25 26 }
以及節點類的冒泡排序算法:
1 package demo; 2 3 /** 4 * @author Lcc 5 * 6 */ 7 public class BubbleSort { 8 9 public Node[] bubbleSort(Node[] a) { 10 11 for (int i = 0; i < a.length; i++) { 12 for (int j = 0; j < a.length; j++) { 13 if (a[i].getValue() > a[j].getValue()) { 14 Node temp = a[i]; 15 a[i] = a[j]; 16 a[j] = temp; 17 } 18 } 19 } 20 System.out.println(a[1].toString());// 沒有使用mock時輸出:"它本來的值是:2 21 return a; 22 } 23 24 }
現在我們需要測試冒泡排序方法,當然由於這個方法比較簡單其實不用mock也可以,但是博主一時間也想不出來有什么好的例子。如果有什么疑問,非常歡迎和博主討論。
現在使用沒有mock的測試方法(實際情況下,不用mock的情況比較少。這里僅作為對比)
package demo; import org.junit.Assert; import org.junit.Test; /** * @author Lcc * */ public class BubbleSortTest { BubbleSort bubbleSort = new BubbleSort(); /** * bubbleSort的測試方法 */ @Test public void testBubbleSort() { Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); Node[] nodes = {node1,node2,node3}; bubbleSort.bubbleSort(nodes); Assert.assertEquals(3, nodes[0].getValue()); Assert.assertEquals(2, nodes[1].getValue()); Assert.assertEquals(1, nodes[2].getValue()); } }
這里解釋一下assertEquals的作用:
assertEquals([String message],Object target,Object result) target與result不相等,中斷測試方法,輸出message
assertEquals(a, b) 測試a是否等於b(a和b是原始類型數值(primitive value)或者必須為實現比較而具有equal方法)
assertEquals斷言兩個對象相等,若不滿足,方法拋出帶有相應信息的AssertionFailedError異常。
其他具體的斷言請參照 http://ryxxlong.iteye.com/blog/716428
這里就不一一贅述了。
下面我們來使用mock來測試這個方法:
1 package demo; 2 3 import org.junit.Assert; 4 import org.junit.Test; 5 import static org.mockito.Mockito.*; 6 7 /** 8 * @author Lcc 9 * 10 */ 11 public class BubbleSortTest { 12 13 BubbleSort bubbleSort = new BubbleSort(); 14 15 /** 16 * bubbleSort的測試方法 17 */ 18 @Test 19 public void testBubbleSort() { 20 21 Node node1 = new Node(1); 22 // Node node2 = new Node(2); 23 Node mockNode2 = mock(Node.class); 24 Node node3 = new Node(3); 25 26 when(mockNode2.getValue()).thenReturn(2); 27 when(mockNode2.toString()).thenReturn("現在輸出的就是mock的調用when后你准備的值了"); 28 29 Node[] nodes = {node1,mockNode2,node3}; 30 31 bubbleSort.bubbleSort(nodes); 32 Assert.assertEquals(3, nodes[0].getValue()); 33 Assert.assertSame(mockNode2, nodes[1]);//由於我們mock了node2.getValue()所以不能直接斷言這個方法,應該斷言它的hash碼 34 Assert.assertEquals(1, nodes[2].getValue()); 35 } 36 37 }
現在運行junit test 冒泡排序中的System.out.println輸出的就是我們mock的值。mock簡單的來說就是模擬,不是真實的去執行,而是在調用mock對象的時候返回一個你事先准備好的值,因此我們測試被測方法的時候僅需要准備這個方法調用的類。
代碼和文章寫的不好,感謝瀏覽!希望這篇文章能夠對各位有幫助。