mardi 23 décembre 2014

How to test these kinds of methods (from Service layer)

I'm fiddling around with Mockito and Spring MVC. I'm trying to write unit tests for the code I've just written.


This is my CategoryService class:



@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;
}


I've already tested CategoryDao with nearly 100% coverage.


And now I want to test CategoryService, but I have no idea how to test it, I mean methods like: addCategory, getCategoryById, getAllCategories, getCategoiesCount etc.


They're just talking to the DAO pattern, but what if another person changes its logic? I'd be glad if you told me or showed how to write a tests for such short methods.


As far as CategoryService is concerned, I only wrote tests for 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));
}


Thank you very much for help :)


Best regards, Tom


Aucun commentaire:

Enregistrer un commentaire