2、UnitTest.cpp
1. /* 2. * Copyright (c) 2008, 胡添发(hutianfa@163.com) 3. * 4. * 简单的单元测试框架 5. * 6. */ 7. #include "UnitTest.h" 8. 9. /* 10. * VC中没有sleep函数,自己写一个 11. * wait单位是毫秒 12. */ 13. void sleep(clock_t wait) 14. { 15. clock_t goal; 16. goal = wait + clock(); 17. while( goal > clock() ) 18. { 19. ; 20. } 21. } 22. 23. /* 24. * 存放测试信息和错误信息的全局变量 25. */ 26. char *errors[100] = {""}; 27. int errorCount = 0; 28. int testCount=0; 29. time_t startTime, endTime; 30. 31. /* 32. * 添加错误信息 33. */ 34. void addError(char *msg) 35. { 36. char error[100] = "Test '"; 37. strcat(error, msg); 38. strcat(error, "' is failed!"); 39. errors[errorCount] = new char[100]; 40. strcpy(errors[errorCount], error); 41. errorCount ++; 42. } 43. 44. /* 45. * 添加错误信息,带预期结果与实际结果参数 46. */ 47. void addError(char *msg, int expect, int actual) 48. { 49. char error[100] = "Test '"; 50. char num[10]; 51. strcat(error, msg); 52. strcat(error, "' is failed!"); 53. strcat(error, " Expected: "); 54. strcat(error, itoa(expect, num, 10)); 55. strcat(error, " , actual: "); 56. strcat(error, itoa(actual, num, 10)); 57. errors[errorCount] = new char[100]; 58. strcpy(errors[errorCount], error); 59. errorCount ++; 60. } 61. 62. /* 63. * 判断是否取值为真 64. */ 65. void assertTrue(char *msg, bool actual) 66. { 67. sleep(10); 68. testCount++; 69. if(actual) 70. { 71. printf("."); 72. } 73. else 74. { 75. printf("F"); 76. addError(msg); 77. } 78. } 79. 80. /* 81. * 判断预期结果和实际结果是否相符 82. */ 83. void assertEquals(char *msg, int expect, int actual) 84. { 85. sleep(10); 86. testCount++; 87. if(expect == actual) 88. { 89. printf("."); 90. } 91. else 92. { 93. printf("F"); 94. addError(msg, expect, actual); 95. } 96. } 97. 98. /* 99. * 测试报告 100. */ 101. void testReport() 102. { 103. printf("\n\nTotal run Tests:"); //测试概要信息 104. printf("%d", testCount); 105. printf(", passed:%d", testCount-errorCount); 106. printf(", failed:%d\n", errorCount); 107. printf("Test escaped time: %6.3f seconds\n", (double)(endTime-startTime)/1000.0); 108. 109. if(errorCount>0) //测试失败的详细信息 110. { 111. printf("\n**************** Failed Test's Detail ****************\n\n"); 112. 113. for(int i=0; i<errorCount; i++) 114. { 115. printf(" %d: ", i+1); 116. printf(errors[i]); 117. printf("\n"); 118. } 119. printf("\n**************** End of Failed Detail ****************\n\n"); 120. } 121. else //所有测试都通过 122. { 123. printf("\n****** All Tests had Passed! ******\n\n"); 124. } 125. } 126. 127. /* 128. * 初始化测试,开始计时 129. */ 130. void init() 131. { 132. printf("\n****** Test start ******\n"); 133. startTime = clock(); 134. } 135. 136. /* 137. * 结束测试,结束计时,打印报告 138. */ 139. void end() 140. { 141. endTime = clock(); 142. testReport(); 143. } 144. |
3、实际测试结果截图:
相关阅读: