如何給一個私有方法做單元測試
給類的公有方法做單元測試,很簡單,new一個對象,設好入口參數后,調用這個方法,比較期望值和實際值即可。給一個類的私有方法做單元測試,也不麻煩,先通過反射獲取這個方法,然后將這個方法的可訪問性強制設為true,這樣的話,這個私有方法就可以被調用了。 代碼如下://被測試方法private Double format(Double fileSize){Double size = fileSize;size = size / 1024 / 1024;size = (int)(size.doubleValue() * 10 + 0.5) / 10.0;return size;}@Testpublic void testFormat(){ClientDownloadAction action = new ClientDownloadAction();double size = 3732930;Class class1 = action.getClass();try {Method format = class1.getDeclaredMethod("format", Double.class);format.setAccessible(true);//設為可見Double result = (Double)format.invoke(action, size);Double expect = 3.6;Assert.assertEquals(expect, result);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}
//被測試方法 private Double format(Double fileSize){ Double size = fileSize; size = size / 1024 / 1024; size = (int)(size.doubleValue() * 10 + 0.5) / 10.0; return size; } @Test public void testFormat(){ ClientDownloadAction action = new ClientDownloadAction(); double size = 3732930; Class class1 = action.getClass(); try { Method format = class1.getDeclaredMethod("format", Double.class); format.setAccessible(true);//設為可見 Double result = (Double)format.invoke(action, size); Double expect = 3.6; Assert.assertEquals(expect, result); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } |
posted on 2014-06-20 11:27 順其自然EVO 閱讀(412) 評論(0) 編輯 收藏 所屬分類: 測試學習專欄