具有另一个返回void的方法的方法的单元测试

时间:2014-08-01 11:13:17

标签: java junit mockito

我要测试的实际方法:

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());"

我如何为这个删除方法编写一个模拟器?

2 个答案:

答案 0 :(得分:0)

试试这个:

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

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

如果你想抛出异常

答案 1 :(得分:0)

您可以使用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);

    }
}