簡體   English   中英

具有另一個返回void的方法的方法的單元測試

[英]Unit test of a method that has another method which returns void

我要測試的實際方法:

public Boolean deletePatientChart(IPRDTO clientDto, Long bookShelfId,
            Long patientChartId) throws BusinessException, Exception {

        BookShelves bookShelves = bookshelvesRepository.findOne(bookShelfId);
        if (bookShelves.getType().equals("SECONDARY")) {
            UserChartShelves userChartShelves = bookshelvesRepository
                    .getUserPatientChartToDelete(bookShelfId, patientChartId);
            if (userChartShelves != null) {
                userChartShelvesRepository.delete(userChartShelves.getId());
                return true;
            } else {
                throw new BusinessException("noItemToDelete");
            }
        }
        throw new BusinessException("noDeletion");
    }

我的測試代碼:

@Test
public void testDeletePatientChart() throws BusinessException, Exception {
    BookShelves bookShelves =new BookShelves();
    UserChartShelves userChartShelves  =new UserChartShelves();
    Mockito.when(this.bookshelvesRepository.findOne(1l))
            .thenReturn(bookShelves);
    Mockito.when(this.bookshelvesRepository.getUserPatientChartToDelete(1l, 1l))
    .thenReturn(userChartShelves);
    boolean status = this.bookshelfServiceImpl.deletePatientChart(
            clientDto, 1l, 1l);
    Assert.assertTrue(status);
}

在我的測試代碼中,我還沒有進行模擬

"userChartShelvesRepository.delete(userChartShelves.getId());"

我如何為此刪除方法編寫一個模擬文件?

嘗試這個:

Mockito.doNothing().when(userChartShelvesRepository).delete(Mockito.anyObject());

要么

Mockito.doThrow(new Exception()).when(userChartShelvesRepository).delete(Mockito.anyObject());

如果你想拋出異常

您可以使用ArgumentCaptor捕獲傳入的參數並進行驗證

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.junit.Test;
import org.mockito.ArgumentCaptor;


public class TestUnit {

    @Test 
    public void test() {
        TestObj obj = mock(TestObj.class);
        ArgumentCaptor<Long> argCapture = ArgumentCaptor.forClass(Long.class);
        doNothing().when(obj).delete(argCapture.capture());
        obj.delete(10L);
        assertEquals(10L, argCapture.getValue().longValue());
    }

    private static interface TestObj {

        public void delete(Long id);

    }
}

暫無
暫無

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

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