我希望对恢复另一种方法的效果的方法进行JUnit-4测试,这样,如果第一个方法被破坏,测试就不会通过,而是需要两者都正确工作。我该怎么解决这个问题?
想想我下面的代码..。
@Test
public void testRemoveCategory(){
Category newCategory = new Category();
testRecipe.addCategory(newCategory);
testRecipe.removeCategory(newCategory);
assertFalse(testRecipe.getCategories().contains(newCategory));在这段代码中,方法removeCategory(Category category)只能在addCategory(Category category)\已经添加了它的情况下才能从逻辑上删除这个类别。这就产生了两个问题
addCategory必须为removeCategory工作,以便通过测试addCategory不工作,removeCategory也会通过测试,即使它也不工作。我想不出第一个问题的解决方案,但我使用以下代码解决了第二个问题.
@Test
public void testRemoveCategory(){
Category newCategory = new Category();
boolean passesTest;
testRecipe.addCategory(newCategory);
if (!testRecipe.getCategories().contains(newCategory)){
passesTest = false;
}
else
{
testRecipe.removeCategory(newCategory);
if(!testRecipe.getCategories().contains(newCategory))
{
passesTest = true;
}
else
{
passesTest = false;
}
}
assertTrue(passesTest);
}然而,
显然,workaround.
我可以看到,这种普遍的情况经常发生,因为许多方法确实是相互矛盾的。我如何处理这些问题?
发布于 2022-04-04 15:48:18
单元测试只关注一个单元的行为。testRemoveCategory不应该麻烦addCategory是否正常工作。您可以通过反射或其他方法(如addCategories )添加新类别。您不能测试方法的所有排列。
我不知道Recipe如何存储这些类别的实现细节。如果类别持有人未通过构造函数传递或注入,您可以尝试以下方法:
。
@Test
public void testRemoveCategory() {
// given
Category otherCategory = new Category();
Category newCategory = new Category();
testRecipe.addCategory(otherCategory);
testRecipe.addCategory(newCategory);
// at this point testRecipe should have only two categories: newCategory and otherCategory
// you may add the categories by any other way not only addCategory()
// we are not testing the behaviour of addCategory
// when
testRecipe.removeCategory(newCategory);
// then
// testing the absence of newCategory
assertFalse(testRecipe.getCategories().contains(newCategory));
// testing the presence of otherCategory
assertTrue(testRecipe.getCategories().contains(otherCategory));
// !! but not testing only size of categories
// which may be flaky if there is a bug in removeCategory()
// assertTrue(testRecipe.getCategories().size(), 1);
}最后,If和else在单元测试中都是危险的,人们永远不应该使用它。
希望能帮上忙。
https://stackoverflow.com/questions/71713868
复制相似问题