【问题标题】:How to test DaoImpl methods using Junit and Mockito如何使用 Junit 和 Mockito 测试 DaoImpl 方法
【发布时间】:2019-07-04 02:30:52
【问题描述】:

我正在为我的应用程序使用带有 jdbcTemplate 的 spring,并且我想测试 DaoImpl 类。有插入、更新和检索操作的实现

道类方法

//dummy class
public class PlayerDAOImpl implements PlayerDAO {

@Autowired
private JdbcTemplate jdbcTemplate;


public Integer getPlayer(int playerId) {

    String sql = "SELECT ccount(1) FROM PLAYER WHERE 
     PLAYER_ID = ?";
     return  (jdbcTemplate. queryForObject("Query", new Object[]{playerId}, 
  Integer.class)!=0); //here only throws exception

}
//other methods
}

为此,我编写了 Test 类,它成功执行以进行插入和更新,但在检索它时给出了 nullpointer 异常。

 @RunWith(MockitoJUnitRunner.class)
 class Test{
 @InjectMocks
  PlayerDAOImpl dao;
 @Mock
 JdbcTemplate jdbcTemplate;

  @Test
  public void retrieveResult(){

   Mockito.when(dao.getPlayer(int playerId)).thenReturn(false);

   //Assert Statement

  }}

我已经搜索/尝试过,但没有找到适合我的解决方案。那么如何测试该方法或注入 jdbcTemplate 使其成功。

感谢您的帮助!!

【问题讨论】:

    标签: spring mockito junit4 jdbctemplate


    【解决方案1】:

    问题是您试图模拟被测类 (PlayerDAOImpl) 而不是它的依赖项 (JdbcTemplate)。

    将你的 mock 更改为:

    Mockito.when(jdbcTemplate.queryForObject(Mockito.any(), Mockito.any(), Mockito.any()).thenReturn(COUNT);
    

    其中COUNTInteger,然后在dao.getPlayer 的返回值上写下你的断言。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-13
      • 1970-01-01
      • 2018-12-23
      • 2020-01-20
      • 1970-01-01
      • 2021-11-06
      相关资源
      最近更新 更多