描述:写单元测试,需要注意校验结果,以及代码覆盖率!
解决方案:实例
/**FansCountApp的私有方法addDay方法测试 * * 时间向后推迟一天 * * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ @org.junit.Test public void testAddDay() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ Method method = reflection(FansCountApp.class, "addDay",new Class[]{Date.class,int.class}); FansCountApp app = new FansCountApp(); // 向后推迟一天 @SuppressWarnings("deprecation") String date = String.valueOf(method.invoke(app,new Object[]{new Date(117,3,22,1,0,0),1})); Assert.assertTrue(date.equals("Sun Apr 23 01:00:00 CST 2017")); // 向后推迟两天 @SuppressWarnings("deprecation") String date1 = String.valueOf(method.invoke(app,new Object[]{new Date(117,3,24,1,0,0),2})); Assert.assertTrue(date1.equals("Wed Apr 26 01:00:00 CST 2017")); // 向前提前两天 @SuppressWarnings("deprecation") String date2 = String.valueOf(method.invoke(app,new Object[]{new Date(117,3,25,1,0,0),-2})); Assert.assertTrue(date2.equals("Sun Apr 23 01:00:00 CST 2017")); // 向后推迟0天 @SuppressWarnings("deprecation") String date3 = String.valueOf(method.invoke(app,new Object[]{new Date(117,3,23,1,0,0),0})); Assert.assertTrue(date3.equals("Sun Apr 23 01:00:00 CST 2017")); } 分析:测试的是修改时间方法,Assert.assertTrue就是校验结果和预期猜想的结果是否相等。不好的地方就是,不能校验集合!测试代码覆盖率就要下载eclipse的插件了,用的比较多的好像是 EclEmma,注意:有说的不对的地方,请多多指教!一起学习。