测试案例6种编写方法_一种编写测试的好方法
測試案例6種編寫方法
測試。 我最近一直在考慮測試。 作為我對各種項目所做的代碼審查的一部分,我已經看到了數千行未經測試的代碼。 這不僅是測試覆蓋率統計數據指出這一點的情況,更是該項目中根本沒有任何測試的情況 。 我一直聽到這種悲慘狀況的兩個原因是什么? “我們沒有時間”,緊隨其后的是“完成代碼后就去做”。
我在這里介紹的不是萬能藥。 它涵蓋了單元測試,尤其是接口的單元測試。 接口是好東西。 接口定義合同。 接口,無論接口有多少種實現,都可以輕松,輕松地進行測試。 讓我們看看如何使用此類結構作為示例。
CustomerService是我們的界面。 為了使示例保持簡單,它有兩種方法,下面將進行介紹。 請注意javadoc-這是描述合同的地方。
從圖中可以看到,我們有兩個此類的實現,RemoteCustomerService和CachingCustomerService。 這些的實現未顯示,因為它們無關緊要。 我怎么說呢 很簡單–我們正在測試合同。 我們為接口中的每個方法以及合約的每個排列編寫測試。 例如,對于get(),我們需要測試存在具有給定用戶名的客戶時發生的情況,以及不存在時發生的情況。
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(); }現在,我們對合同進行了測試,并且我們從未提及任何實現。 這意味著兩件事:
- 我們不需要為每個實現重復測試。 這是一件非常好的事情。
- 沒有一個實現正在測試中。 我們可以通過為每個實現添加一個測試類來糾正此問題。 由于每個測試類幾乎都是相同的,因此我將僅演示RemoteCustomerService的測試。
就是這樣! 現在,我們有了一種非常簡單的方法來測試任何接口的多個實現,方法是預先進行艱苦的工作,并將測試新實現的工作減少到一個簡單的方法中。
翻譯自: https://www.javacodegeeks.com/2013/06/a-good-lazy-way-to-write-tests.html
測試案例6種編寫方法
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的测试案例6种编写方法_一种编写测试的好方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux表达式不包含(linux表达式
- 下一篇: 使用Spring MVC应用程序配置嵌入