我应该在单元测试中检查实现细节,还是只使用类公共API?

huangapple go评论81阅读模式
英文:

Should I check implementation details or use class public API only in a unit test?

问题

考虑下面的示例:

public class Foo {

    protected List<Integer> arr = new ArrayList<>();

    void add(int i) { arr.add(i); }

    int size() { return 0; }
}

public class FooTest {

    Foo foo = new Foo();

    @Test
    void checkAdd() {
        foo.add(1);
        assertEquals(1, foo.size()); // 失败
        assertEquals(1, foo.arr.size()); // 成功
    }
}

抱歉,我有一个简单的问题,但仍然无法找到答案。在单元测试中检查实现细节是否被视为一种不良做法?显然,通过公共API的某一部分来测试另一部分公共API,很可能会导致不正确的结果。另一方面,实现可能非常复杂,想象一下如果要测试HashMap。

英文:

Consider the following example:

public class Foo {

    protected List&lt;Integer&gt; arr = new ArrayList&lt;&gt;();

    void add(int i) { arr.add(i); }

    int size() { return 0; }
}

public class FooTest {

    Foo foo = new Foo();

    @Test
    void checkAdd() {
        foo.add(1);
        assertEquals(1, foo.size()); // fail
        assertEquals(1, foo.arr.size()); // pass
    }
}

Sorry, I have a lame question but still unable to find an answer. Is it considered as a bad practice to check implementation details as a part unit testing? Obviously testing one part of public API via another part of public API may (and most likely will) lead to incorrect results. On the other side implementation can be very complicated, just imagine if you want to test HashMap.

答案1

得分: 2

没有size()和arr.size()之间的直接连接,如果您想测试是否有另一个列表在满足条件时添加元素,该怎么办?

我认为您应该有另一个测试,检查size()是否返回与arr.size()相同的结果,如果这是预期的行为。
在进行了这个测试之后,您可以假设size()总是会返回预期的结果。

英文:

There is no immediate connection between size() and arr.size(), what if you wanted to test that there is another list that adds elements with a condition?

I think you should have another test that checks if the size() returns the same result as the arr.size() if this is the expected behaviour.
After this test, you can proceed with the assumption that size() always will return the expected results.

答案2

得分: 1

你应该检查公共方法。另外,你不需要检查实现细节,而是通过输入和输出测试每个方法。

英文:

Short Answer:

You should check the public methods. Also you don't need to check the implementation details instead test each of the methods by their input and output.

huangapple
  • 本文由 发表于 2020年10月1日 21:39:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64156618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定