简体   繁体   English

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

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

My actual method to be tested: 我要测试的实际方法:

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

My test code: 我的测试代码:

@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);
}

In my test code I have not made a mock for 在我的测试代码中,我还没有进行模拟

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

How can i write a mock for this this delete method? 我如何为此删除方法编写一个模拟文件?

Try this: 尝试这个:

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

or 要么

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

if you want to throw exception 如果你想抛出异常

You can use ArgumentCaptor to capture the passed in argument and verify it 您可以使用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