如何模拟 jdbcTemplate.execute(callableStatementCreator, callableStatementCallback);

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

我正在尝试模拟(Spring 引导、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);
  }
}

我收到以下编译时异常:

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

这条线

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

如何模拟 jdbcTemplate.execute(callableStatementCreator, callableStatementCallback)。如何让它工作?

方法 JdbcTemplate.execute()overloaded

因此,当您使用匹配器 any() 模拟它时,编译器根本不知道您实际指的是哪个方法并抛出错误。

要解决此问题,请在匹配器中提供 class 来解决此歧义。

例如,如果你想模拟

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

使用

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