簡體   English   中英

Mockito 和單元測試——如何控制新對象的創建

[英]Mockito and unit testing - how to control new object creation

我有這個方法進行單元測試:

public class DPService {
    public DPModel saveTreeRecursively(DPDTO dpDTO) {
        DPModel dpModel = new DPModel(dpDTO.getDPKey(), dpDTO.getName());
        DPModel savedDpModel = dpDAO.save(dpModel);
        Long dpId = savedDPModel.getDpId();

        // after some operations
        return savedDpModel;
    }
}

測試類是:

public class DPServiceTest {
    @Test
    public void testSaveTreeRecursively() {
        DPModel dpModel1 = new DPModel(dpKey, dpName); // same dpKey and dpName 
        //used in the SUT method to create DPModel, dpModel

        DPModel dpModel2 = new DPModel(dpKey, dpName);
        dpModel2.setDPId(123L);

        // SUT
        DPService dpService = new DPService();

        // creating a mock DAO so that, the unit testing is independent of real DAO
        DPDaoMock dpDaoMock = Mockito.mock(DPDao.class);

        // we want to control the mock dpDAO so that it returns 
        // the model we want that the below SUT method uses; basically we are pretending that
        // the dpDAO saved the dpModel1 with a primary key, dpId = 123
        // and returned the dpModel2 saved in the database.
        Mockito.when(dpDaoMock.save(dpModel1)).thenReturn(dpModel2);

        DPModel dpModel3 = dpService.saveTreeRecursively(dpDTO);

        assertEquals(dpModel3.getDpID(), 123L);
    }
}

所以很明顯,SUT 方法失敗了:

Long dpId = savedDPModel.getDpId();

因為在 SUT 方法中創建的實例與我們希望在dpDaoMock使用的dpDaoMock

那么我該如何克服這個問題呢? 有沒有其他更好的方法來模擬 DAO?

謝謝

一些選項。

抽象工廠

DPModel的工廠接口可以作為DPService的依賴DPService 這樣,工廠方法(工廠的)的返回值可以被模擬並用於斷言。

請參考抽象工廠模式

匹配器

Mockito 匹配器可用於檢查模擬方法的參數:

Mockito.when(dpDaoMock.save(Matchers.any())).thenReturn(dpModel2);

或更嚴格的例子:

Mockito.when(dpDaoMock.save(Matchers.argThat(new ArgumentMatcher<DPModel>() {
    @Override
    public boolean matches(Object argument) {
        DPModel dpModel = (DPModel) argument;
        return dpModel.getDpId().equals(123L);
    }
}))).thenReturn(dpModel2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM