2016-07-14 197 views
1

我有一個應用程序與DAO如下。我想要這個班級。我的類看起來像這樣。Spring jdbcTemplate Junit

public class DaoImpl implements Dao{ 

    @Override 
    public User getUserInfo(String userid) { 
     return getTemplate().queryForObject(QUERY, new Object[] { userid }, 
       new BeanPropertyRowMapper<User>(User.class)); 
    } 

    } 

我的JUnit類看起來像這樣

@RunWith(SpringJUnit4ClassRunner.class) 
public class DaoImplTests{ 

    @Autowired 
    private Dao dao; 

    @Mock 
    JdbcTemplate jdbcTemplate; 

    @Test 
    public void testUsingMockito() { 
     try { 
      User mockedUserInfo = new User(); 
      //setters 
      mockedUserInfo.setXXX; 
      mockedUserInfo.setYYY; 

      Mockito.when(((JdbcDaoSupport)dao.getTemplate())).thenReturn(jdbcTemplate); 
      Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(Object[].class), 
        Mockito.any(RowMapper.class))).thenReturn(mockedUserInfo); 
      User userInfo = dao.getUserInfo(""); 
      Assert.assertNotNull(userInfo); 
      Assert.assertEquals(mockedUserInfo.getXXX(), userInfo.getXXX()); 
      //few more assertions 
     } catch (Exception e) { 
      Assert.fail(" : " + e.getMessage()); 
     } 
    } 

} 

當我執行我獲得以下從異常的Mockito這個測試用例。

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'. 
For example: 
    when(mock.getArticles()).thenReturn(articles); 

Also, this error might show up because: 
1. you stub either of: final/private/equals()/hashCode() methods. 
    Those methods *cannot* be stubbed/verified. 
2. inside when() you don't call method on mock but on some other object. 
3. the parent of the mocked class is not public. 
    It is a limitation of the mock engine. 

我的查詢:

  1. 如何JUnit的我的課
  2. 該異常來,因爲getJdbcTemplate是最終JdbcDaoSupport類。這種方法有沒有其他選擇?

我使用後Spring jdbcTemplate unit testing

寫我的JUnit不過,貌似這是行不通的。

+1

不要模擬'JdbcTemplate',模擬數據源,例如在內存數據庫中 –

+0

模擬數據庫似乎不適合我,因爲數據庫非常複雜和龐大。 – Javadroider

+0

測試DAO時,不應該模擬數據庫。這種測試應該是集成測試,數據庫在後面運行。請閱讀此處[如何測試數據訪問層?](http://programmers.stackexchange.com/questions/219362/how-to-test-the-data-access-layer) – cheffe

回答

0

您的問題是這一行:

Mockito.when(((JdbcDaoSupport)dao.getTemplate())).thenReturn(jdbcTemplate); 

你道標註了@Autowired,所以它不是一個嘲笑的對象。你想要做的就是使用SpringTestReflectionUtils在dao中將你的jdbcTemplate設置爲你的模擬對象。