简体   繁体   English

使用 JUnit 和 Mockito 对 DAO 类进行单元测试

[英]Unit testing of DAO classes using JUnit and Mockito

I have DaoImpl class:我有 DaoImpl 类:

public class MessageTypeDaoImpl implements MessageTypeDao{

    public int[] createMessageTypes(final List<MessageType> messageTypes){
        String sql = "INSERT INTO MSG_TYPE VALUES(?, ?)";
        return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                MessageType messageType = messageTypes.get(i);
                ps.setString(1, messageType.getMessageId());
                ps.setString(2, messageType.getMessageName());
            }

            public int getBatchSize(){
                return messageTypes.size();
            }
    });
}

And my test:我的测试:

@RunWith(MockitoJUnitRunner.class)
public class MessageTypeDaoImplTest {

@Mock
private JdbcTemplate jdbcTemplate;

@Spy
@InjectMocks
MessageTypeDaoImpl messageTypeDaoImpl;
@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
}
@Test
public void createMessageTypes() {
    int[] returnCount = new int[1];
    List<MessageType> messageTypeList = new ArrayList<MessageType>();
    messageTypeList.add(getSampleMessageType());
    messageTypeDaoImpl.createMessageTypes(messageTypeList);
    doReturn(returnCount).when(messageTypeDaoImpl).createMessageTypes(messageTypeList);
    assertEquals(returnCount, messageTypeDaoImpl.createMessageTypes(messageTypeList));
}
}

public MessageType getSampleMessageType(){
    return new MessageType("messageTypeId", "messageTypeName");
}

Test is successful but when I run junit test with coverage it shows public void setValues() method is not being covered, hence my overall unit test line coverage is below the requirements.测试成功,但是当我使用覆盖率运行 junit 测试时,它显示未覆盖public void setValues()方法,因此我的整体单元测试行覆盖率低于要求。 Can we cover that part?我们可以覆盖那部分吗? And if yes then how we do it?如果是,那么我们如何做到这一点? Thanks.谢谢。

Try this below code spinet.试试下面的代码spinet。 I will cover the code as well.我也会介绍代码。 I check it from my end, and it worked.我从我的最后检查它,它起作用了。

int[] batchInsert=new int[] {1,2};
        try {

            Mockito.doAnswer(invocationOnMock -> {

                PreparedStatement ps = Mockito.mock(PreparedStatement.class);
                BatchPreparedStatementSetter psr = invocationOnMock.getArgument(1);
                psr.setValues(ps, 1);
                return batchInsert;

            }).when(jdbcTemplate).batchUpdate(anyString(),  Mockito.any(BatchPreparedStatementSetter.class));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM