[英]Spring jdbcTemplate unit testing
我是Spring的新手,對JUnit和Mockito只有一點經驗
我有以下方法需要單元測試
public static String getUserNames(final String userName {
List<String> results = new LinkedList<String>();
results = service.getJdbcTemplate().query("SELECT USERNAME FROM USERNAMES WHERE NAME = ?", new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return new String(rs.getString("USERNAME");
}
}
return results.get(0);
},userName)
有沒有人對如何使用JUnit和Mockito實現這一點有任何建議?
非常感謝你提前!
如果你想進行純單元測試,那么就行了
service.getJdbcTemplate().query("....");
您將需要模擬Service,然后使用service.getJdbcTemplate()方法返回模擬JdbcTemplate對象,然后模擬模擬JdbcTemplate的查詢方法以返回所需的List。 像這樣的東西:
@Mock
Service service;
@Mock
JdbcTemplate jdbcTemplate;
@Test
public void testGetUserNames() {
List<String> userNames = new ArrayList<String>();
userNames.add("bob");
when(service.getJdbcTemplate()).thenReturn(jdbcTemplate);
when(jdbcTemplate.query(anyString(), anyObject()).thenReturn(userNames);
String retVal = Class.getUserNames("test");
assertEquals("bob", retVal);
}
以上不需要任何Spring支持。 如果您正在進行集成測試,而您實際上想要測試數據是否正確地從數據庫中提取,那么您可能希望使用Spring Test Runner。
您需要使用Spring Test來執行此操作。 看看文檔:
http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html
你需要使用@RunWith創建一個測試,並使用帶有@ContextConfiguration的spring conf:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config.xml")
public class SpringAppTests {
@Autowired
private HelloService helloService;
@Test
public void testSayHello() {
Assert.assertEquals("Hello world!", helloService.sayHello());
}
}
在這里您可以從文檔中獲得一些解釋:
@RunWith
@Runwith(SpringJUnit4ClassRunner.class),開發人員可以實現標准的JUnit 4.4單元和集成測試,同時獲得TestContext框架的好處,例如支持加載應用程序上下文,依賴注入測試實例,事務測試方法執行等。
@ContextConfiguration
@ContextConfiguration定義類級元數據,用於確定如何為集成測試加載和配置ApplicationContext。 具體來說,@ ContextConfiguration聲明應用程序上下文資源位置或將用於加載上下文的帶注釋的類。 希望能有所幫助
希望能有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.