Braham Shakti
Braham Shakti

Reputation: 1456

How to write Junit for jdbcTemplate call method

I am stuck in junit, I have to write junit for one of my dao mathod, here is my test code

@Test
public void testUpdateFeedback() throws SQLException {
    List<SqlParameter> parameters = Arrays.asList(new SqlParameter(Types.NVARCHAR));
    Mockito.when(jdbcTemplate.call(Mockito.any(CallableStatementCreator.class),
            eq(parameters))).thenReturn(Mockito.anyMap());
    Integer count = daoImpl.updateFeedBack(...somedata...);
    assertEquals(1, count);
}

but it is throwing error

Invalid use of argument matchers!

2 matchers expected, 1 recorded:

here is my dao code

public Integer updateFeedBack(Requestfeedback somedata) {
    List<SqlParameter> parameters = Arrays.asList(new SqlParameter(Types.NVARCHAR));
    jdbcTemplate.call(new CallableStatementCreator() {
        @Override
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
            CallableStatement cs = con.prepareCall("call updatefeedbackprocedure(?)");
            int count = 0;
            cs.setString(++count, "abc");
            return cs;
        }
    }, parameters);
    return 1;
}

Even If I use below code it does not work

Mockito.when(jdbcTemplate.call(Mockito.any(CallableStatementCreator.class), Mockito.anyList())).thenReturn(Mockito.anyMap());

please help thanks.

Upvotes: 1

Views: 704

Answers (1)

Ken Chan
Ken Chan

Reputation: 90417

Seriously I do not recommend to test with Mock for this case since you are testing the DAO which is the data access layer , and the best way to test the data access layer is test with the actual DB but not the mock. Because in the end you still need to have some kind of integration test to verify your application can really get and update data from/to DB correctly and this DAO is the most appropriate place to do it.

You can check with Testcontainers which allows you to test with a containerised version of the DB which in theory should be very close to your actual production DB. You can refer to this for an example.

Upvotes: 2

Related Questions