英文:
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<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()); // 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论