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

标签 java spring spring-boot mockito jdbctemplate

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

我收到以下编译时异常:

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() 模拟它时,编译器根本不知道您实际指的是哪个方法并抛出错误。

要修复此问题,请在匹配器中提供一个类来解决此歧义。

例如,如果你想模拟

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

使用

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

关于java - 如何模拟 jdbcTemplate.execute(callableStatementCreator, callableStatementCallback);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57191211/

相关文章:

postgresql - 为 child + 新字段重复使用复合键

spring - 设置 Spring Profile 变量

java - 数组索引越界异常

json - 创建一个 JSON 对象以在 Spring Boot 测试中发布

Spring Boot 镜像上传和服务

java - 不满意的依赖异常 : Error creating bean with name 'homeController' : Unsatisfied dependency expressed through field 'dao'

java - 数据从内存数据库中自动删除

java - Jsoup:无法选择 tbody id 中的所有行

java - 电脑崩溃后无法启动eclipse

java - 为什么 spring webflux 默认选择 jetty 然后失败?