我在擺弄Mockito和Spring MVC。我正在爲我剛剛編寫的代碼編寫單元測試。如何測試這些類型的方法(來自服務層)
這是我CategoryService類:
@Service
public class CategoryService {
@Autowired
@Qualifier("categoryDaoImpl")
private CategoryDao categoryDao;
public void addCategory(Category category) {
category.setId(getLastCategoryId() + 1);
categoryDao.addCategory(category);
}
public Category getCategoryById(int id) {
return categoryDao.getCategoryById(id);
}
public List<Category> getCategories() {
return categoryDao.getAllCategories();
}
public int getCategoriesCount() {
return categoryDao.getCategoriesCount();
}
public int getLastCategoryId() {
if (categoryDao.getAllCategories().size() == 0) {
return 0;
}
return Collections.max(categoryDao.getAllCategories()).getId();
}
public CategoryDao getCategoryDao() {
return categoryDao;
}
public void setCategoryDao(CategoryDao categoryDao) {
this.categoryDao = categoryDao;
}
我已經測試CategoryDao有近100%的覆蓋率。
現在我想測試CategoryService,但我不知道如何來測試它,我的意思是像方法:addCategory,getCategoryById,getAllCategories,getCategoiesCount等
他們只是聊到DAO模式,但是如果另一個人改變其邏輯呢?如果你告訴我或者如何寫出這種簡短方法的測試,我會很高興。
至於CategoryService而言,我只寫了試驗getLastCategoryId():
@Test
public void shouldGetLastCategoryIdWhenListIsEmpty() {
//given
List<Category> list = new ArrayList<Category>();
Mockito.when(categoryDao.getAllCategories()).thenReturn(list);
//when
int lastCategoryId = categoryService.getLastCategoryId();
//then
assertThat(lastCategoryId, is(0));
}
@Test
public void shouldGetLastCategoryIdWhenListIsNotEmpty() {
//given
List<Category> list = new ArrayList<Category>();
list.add(new Category(1, "a", "a"));
list.add(new Category(3, "a", "a"));
list.add(new Category(6, "a", "a"));
Mockito.when(categoryDao.getAllCategories()).thenReturn(list);
//when
int lastCategoryId = categoryService.getLastCategoryId();
//then
assertThat(lastCategoryId, is(6));
}
非常感謝您的幫助:)
最好的問候, 湯姆
這是爲什麼使用構造函數注入而不是字段注入的一個很好的例子:您可以使用Mockito或Spock中的模擬DAO創建服務對象並驗證適當的交互。 (我也建議看看Spring Data而不是手寫你自己的DAO類。) – chrylis