單元測試就像幫程式買一份最基本的終身保險
一旦有了「完整的」unit test,結合CI流程,我們便可以放心地進行refactory、新增功能,甚至是運用 TDD的方式讓測試跟開發流程完美結合在一起。
但寫出來的測試是否「有效」?往往是programmer 剛開始著手撰寫 test code 時所遇到迷思。
「莫忘初衷」,這次主題來講講如何讓 unit test 不要流於形式。
16. 20% test , kill 80% problem
Integration testAcceptance test Manual testMonkey test
Other tests ...
Unit test
Program
Stress test
Clients / End users
31. PowerMockito
A more powerful unit test mocking
framework
● Mock private methods
● Mock static methods
● to let static methods throw exceptions
● Whitebox inject
45. Throw Exception
public static LocalDate parseDate(String str) throws InvalidDateFormatException {
if(str.contains( /*... */)) {
throw new InvalidDateFormatException("Date format should be yyyy-mm-dd");
}
//... more
return result;
}
46. private TenMaxHourlyReport parseTenMaxReport(String reportXml) throws ParseException {
if(reportXml.contains("bad xml format")) {
throw new ParseException("unsupport xml format", 0);
}
TenMaxHourlyReport report = new TenMaxHourlyReport();
report.setImpression(100);
report.setRequestCount(1000);
return report;
}
private void updateRecordFromRemoteReport(TenMaxHourlyReport src, EbaxHourlyReport
target) {
target.setRequestCount(src.getRequestCount());
target.setImpreCount(src.getImpression());
// series properties to assign ...
}
52. Convention of test
● Naming of test function
● Construction of test function
● Readable content
● Libraries for test
53.
54. from Clean Code Ch#9
What makes a clean test?
Three things. Readability, readability, and readability.
Readability is perhaps even more important in unit tests than it is in production
code.
是甚麼造就了一個整潔的測試?
三件事,可讀性、可讀性,還是可讀性。可讀性,在單元測試裡可能比在產品程式裡還
要重要。
55. Accessory
● JUnit5
@Test
@DisplayName("GIVEN: DB 存在 2016-06-30 09:00:00 的 AdxHourly 資料,和 Hourly 資料 "
+ "WHEN: 呼叫 compareWithHourlyReport THEN: 沒有任何錯誤訊息 ")
void test_compareWithHourlyReport_with_compare_success() {
// TODO ...
}
● JUnit4 - extends BlockJUnit4ClassRunner.class
Readable test name