持續整合之路——服務層的單元測試

來源:互聯網
上載者:User

        在完成了資料訪問層的單元之後,接下來看如何編寫服務層(Service)的單元測試。服務層應該是整個系統中得重中之重,嚴密的商務邏輯設計保證了系統穩定運行,所以這一層的單元測試也應該占很大比重。雖然一般情況下單元測試應該盡量通過mock剝離依賴,但是由於在當前的項目中資料訪問層使用spring-data架構,並沒有包含太多的邏輯,因此我就把服務層和資料訪問層放在做了一個偽單元測試。

        一、一般邏輯的單元測試。

        這裡採用的方式和資料訪問層幾乎是一樣的,主要包含三步:

        1. 通過@DatabaseSetup指定測試用資料集

        2. 執行被測試方法

        3. 通過Dao從資料庫中查詢資料驗證執行結果

        假設要被測試的代碼方法是:

@Service@Transactional(readOnly = true)public class ShopServiceImpl extends BaseService implements ShopService{    private Logger logger = LoggerFactory.getLogger(ShopServiceImpl.class);    @Transactional(readOnly = false)    public Floor addFloor(String buildingName, int floorNum, String layout) {        //如果已經存在對應的樓層資訊,則拋出已經存在的異常資訊        Floor floor = floorDao.findByBuildingNameAndFloorNum(buildingName, floorNum);        if (floor != null) {            throw new OnlineShopException(ExceptionCode.Shop_Floor_Existed);        }                //如果不存在對應的商場資訊,則添加新的商場        Building building = buildingDao.findByName(buildingName);        if (building == null) {            building = new Building();            building.setName(buildingName);            buildingDao.save(building);        }         //添加並返回樓層資訊        floor = new Floor();        floor.setBuilding(building);        floor.setFloorNum(floorNum);        floor.setMap(layout);        floorDao.save(floor);        return floor;    }}

其對應的介面是:

public interface ShopService {    public Floor addFloor(String buildingName, int floorNum, String layout);}

        這段邏輯代碼的意思十分簡單和直白,那麼要編寫的單元的測試必須要包含所有分支情況:a. 商場和樓層資訊都存在的,拋出異常 b. 商場存在,而樓層不存在, 樓層資訊都被添加的。 c.  商場和樓層都不存在,全部新增。這裡就以第一種情況為例,先準備測試資料:

<?xml version="1.0" encoding="UTF-8"?><dataset>    <building id="1" name="New House"/>    <floor id="1" building="1" floor_num="2"/></dataset>

接著編寫測試案例,注意要必須得註解不能忘掉:

  

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext-test.xml")@Transactional@TestExecutionListeners({        DependencyInjectionTestExecutionListener.class,        DirtiesContextTestExecutionListener.class,        CustomTransactionDbUnitTestExecutionListener.class,        ForeignKeyDisabling.class})public class ShopServiceTest {    @Autowired    private ShopService shopService;    @Test    @DatabaseSetup("shop/ShopService-addFloorExistException-dataset.xml")    public void testAddFloorExistException(){        try {            shopService.addFloor("New House", 2, "");            fail();        } catch(Exception e){            assertTrue(e instanceof OnlineShopException);            assertEquals(ExceptionCode.Shop_Floor_Existed.code(), ((OnlineShopException)e).getCode());        }    }}

這個測試和資料訪問層的測試看起來沒有什麼兩樣。

        二、使用Mock對象隔離第三方介面

        軟體開發中一般都存在和第三方整合的情況,比如調用新浪的認證、百度的地圖等等。那麼在編寫測試的時候,基於效率的考慮,一般情況不會真的去調用這些遠程API(當然應該有其他測試可以及時發現第三方介面的變化),而是假定它們一直會返回預期的結果。這個時候就需要用到mock對象,來類比這些API產生相應的結果。

        在這裡,我是用了mockito,使用十分方便。假如現在使用者登入時,需要去第三方系統驗證,那麼現在來看如何對這個情境進行測試。還是先來看被測試的方法:

private boolean validateUser(String inputName, String inputPassword) {        return thirdPartyAPI.authenticate(inputName, inputPassword);}

 其中thirdPartyAPI就是第三方用來認證的API。下面來看測試代碼:

public class UserServiceTest {    @Autowired    private UserService userService;    private ThirdPartyAPI mockThirdPartyAPI = mock(ThirdPartyAPI.class);        @Test    public void testLogin(){        //指定mock對象特定操作的返回結果        when(mockThirdPartyAPI.authenticate("jiml", "jiml")).thenReturn(true);        //通過Setter用mock對象替換由Spring初始化的第三方依賴        ((UserServiceImpl)userService).setThirdPartyAPI(mockThirdPartyAPI);        boolean loginStatus = userService.login("jiml", "jiml");        assertTrue(loginStatus);    }}

      其實服務層的測試並沒有太多的新東西,而最關鍵的問題是如何把邏輯中各個分支都能測試到,使測試真正起到為軟體品質保駕護航的作用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.