如何使用 Junit 和 Mockito 测试 DaoImpl 方法

How to test DaoImpl methods using Junit and Mockito

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

道class方法

//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
}

为此,我编写了测试 class,它成功执行了插入和更新,但在检索它时出现空指针异常。

 @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

  }}

我有 googled/tried 但没有找到适合我的解决方案。那么如何测试该方法或注入 jdbcTemplate 以便它成功。

感谢帮助!!

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

将您的模拟更改为类似:

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

其中 COUNT 是一个 Integer,然后在 dao.getPlayer 的 return 值上写下你的断言。