首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何进行依赖于另一种方法操作的JUnit测试?

如何进行依赖于另一种方法操作的JUnit测试?
EN

Stack Overflow用户
提问于 2022-04-02 00:06:15
回答 1查看 49关注 0票数 0

我希望对恢复另一种方法的效果的方法进行JUnit-4测试,这样,如果第一个方法被破坏,测试就不会通过,而是需要两者都正确工作。我该怎么解决这个问题?

想想我下面的代码..。

代码语言:javascript
复制
    @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)\已经添加了它的情况下才能从逻辑上删除这个类别。这就产生了两个问题

  1. addCategory必须为removeCategory工作,以便通过测试
  2. ,如果addCategory不工作,removeCategory也会通过测试,即使它也不工作。

我想不出第一个问题的解决方案,但我使用以下代码解决了第二个问题.

代码语言:javascript
复制
    @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.

  • still并不能解决第一个问题。

我可以看到,这种普遍的情况经常发生,因为许多方法确实是相互矛盾的。我如何处理这些问题?

EN

回答 1

Stack Overflow用户

发布于 2022-04-04 15:48:18

单元测试只关注一个单元的行为。testRemoveCategory不应该麻烦addCategory是否正常工作。您可以通过反射或其他方法(如addCategories )添加新类别。您不能测试方法的所有排列。

我不知道Recipe如何存储这些类别的实现细节。如果类别持有人未通过构造函数传递或注入,您可以尝试以下方法:

  • 定义在给定块
  • 的测试下单元的初始状态,尝试在阻塞
  • 时更改单元的状态,然后断言最终状态

代码语言:javascript
复制
@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);
}

最后,Ifelse在单元测试中都是危险的,人们永远不应该使用它。

希望能帮上忙。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71713868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档