Thiagarajan Ramanathan
Thiagarajan Ramanathan

Reputation: 1124

How to mock jdbcTemplate.execute(callableStatementCreator, callableStatementCallback);

I'm trying to mock (Spring boot, JUnit, Oracle)

jdbcTemplate.execute(CallableStatementCreator, CallableStatementCallback);

public class ExceptionTest
{
  @Autowired
  private SecurityDAOImpl securityDAOImplMock;

  @Mock
  private JdbcTemplate jdbcTemplate;

  @Autowired
  private JdbcTemplate resetJdbcTemplate;

  @Before
  public void init() throws Exception
  {
    securityDAOImplMock = spy(new SecurityDAOImpl());
    MockitoAnnotations.initMocks(this);
  }

  @SuppressWarnings("unchecked")
  @Test(expected = SecurityDAOException.class)
  public void testUpdateProfileException()
  {
    DataAccessException dataAccessException = new DataAccessException("Mock Exception",
        new Exception("Mocked DataAccessException"))
    {
      private static final long serialVersionUID = 1L;
    };
    ReflectionTestUtils.setField(securityDAOImplMock, "jdbcTemplate", jdbcTemplate);
    doThrow(dataAccessException).when(jdbcTemplate).execute(any(), any());
    securityDAOImplMock.isTooManyFailedAttempt("", 7, "", "");
  }

  @After
  public void reset()
  {
    ReflectionTestUtils.setField(securityDAOImplMock, "jdbcTemplate", resetJdbcTemplate);
  }
}

I'm getting the following compile time exception:

The method execute(PreparedStatementCreator, PreparedStatementCallback<Object>) is ambiguous for the type 

on this line

doThrow(securityDAOException).when(jdbcTemplate).execute(any(), any());

How to mock jdbcTemplate.execute(callableStatementCreator, callableStatementCallback).How to make this work?

Upvotes: 0

Views: 3582

Answers (1)

Pavel Smirnov
Pavel Smirnov

Reputation: 4799

Method JdbcTemplate.execute() is overloaded.

So when you mock it using matcher any() the compiler simply does not know which method you actually mean and throws an error.

To fix that supply a class in the matcher to resolve this ambiguity.

For example, if you want to mock

JdbcTemplate.execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action)

use

doThrow(securityDAOException).when(jdbcTemplate).execute(any(PreparedStatementCreator.class), any(PreparedStatementCallback.class));

Upvotes: 2

Related Questions