【发布时间】:2014-12-23 15:42:08
【问题描述】:
我在摆弄 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;
}
我已经测试了几乎 100% 覆盖率的 CategoryDao。
现在我想测试 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 类。)
标签: spring unit-testing spring-mvc junit mockito