一种编写测试的好方法
測(cè)試。 最近我一直在考慮進(jìn)行測(cè)試。 作為我對(duì)各種項(xiàng)目所做的代碼審查的一部分,我已經(jīng)看到了數(shù)千行未經(jīng)測(cè)試的代碼。 這不僅是測(cè)試覆蓋率統(tǒng)計(jì)數(shù)據(jù)指出這一點(diǎn)的情況,還更多是該項(xiàng)目中根本沒(méi)有任何測(cè)試的情況 。 我一直聽(tīng)到這種悲慘狀況的兩個(gè)原因? “我們沒(méi)有時(shí)間”,緊隨其后的是“完成代碼后就去做”。
我在這里展示的不是萬(wàn)能藥。 它涵蓋了單元測(cè)試,尤其是接口的單元測(cè)試。 接口是好東西。 接口定義合同。 接口,無(wú)論接口有多少種實(shí)現(xiàn)方式,都可以輕松,輕松地進(jìn)行測(cè)試。 讓我們看看如何使用此類結(jié)構(gòu)作為示例。
CustomerService是我們的界面。 為了使示例保持簡(jiǎn)單,它有兩種方法,下面將進(jìn)行介紹。 注意javadoc-這是描述合同的地方。
從圖中可以看到,我們有兩個(gè)此類的實(shí)現(xiàn),RemoteCustomerService和CachingCustomerService。 這些的實(shí)現(xiàn)沒(méi)有顯示,因?yàn)樗鼈儫o(wú)關(guān)緊要。 我怎么說(shuō)呢 很簡(jiǎn)單–我們正在測(cè)試合同。 我們?yōu)榻涌谥械拿總€(gè)方法以及合同的每個(gè)排列編寫測(cè)試。 例如,對(duì)于get(),我們需要測(cè)試存在具有給定用戶名的客戶時(shí)發(fā)生的情況,以及不存在時(shí)發(fā)生的情況。
public abstract class CustomerServiceTest {@Testpublic void testCreate(){CustomerService customerService = getCustomerService();Customer customer = customerService.create(new Customer("userNameA"));Assert.assertNotNull(customer);Assert.assertEquals("userNameA",customer.getUserName());}@Test(expected = DuplicateCustomerException.class)public void testCreate_duplicate(){CustomerService customerService = getCustomerService();Customer customer = new Customer("userNameA");customerService.create(customer);customerService.create(customer);}@Testpublic void testGet(){CustomerService customerService = getCustomerService();customerService.create(new Customer("userNameA"));Customer customer = customerService.get("userNameA");Assert.assertNotNull(customer);Assert.assertEquals("userNameA",result.getUserName());}@Test(expected = CustomerNotFoundException.class)public void testGet_noUser(){CustomerService customerService = getCustomerService();customerService.get("userNameA");}public abstract CustomerService getCustomerService(); }現(xiàn)在,我們已經(jīng)對(duì)合同進(jìn)行了測(cè)試,并且在任何時(shí)候都沒(méi)有提到任何實(shí)現(xiàn)。 這意味著兩件事:
- 我們不需要為每個(gè)實(shí)現(xiàn)重復(fù)測(cè)試。 這是一件非常好的事情。
- 沒(méi)有一個(gè)實(shí)現(xiàn)正在測(cè)試中。 我們可以通過(guò)為每個(gè)實(shí)現(xiàn)添加一個(gè)測(cè)試類來(lái)糾正此問(wèn)題。 由于每個(gè)測(cè)試類幾乎都是相同的,因此我將僅演示RemoteCustomerService的測(cè)試。
就是這樣! 現(xiàn)在,我們有了一種非常簡(jiǎn)單的方法來(lái)測(cè)試任何接口的多個(gè)實(shí)現(xiàn),方法是預(yù)先進(jìn)行艱苦的工作,并將測(cè)試新實(shí)現(xiàn)的工作減少到一個(gè)簡(jiǎn)單的方法中。
翻譯自: https://www.javacodegeeks.com/2013/06/a-good-lazy-way-to-write-tests.html
總結(jié)
以上是生活随笔為你收集整理的一种编写测试的好方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java垃圾回收(4)
- 下一篇: 华为电脑翻译快捷键(华为手机快捷翻译功能