java 如何 JUnit 测试迭代器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14920164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to JUnit test a iterator
提问by JJ Liu
For example, how do I test:
例如,我如何测试:
ArrayList<String> list = new ArrayList<String>();
list.iterator();
How to test this "iterator()
" method?
如何测试这个“ iterator()
”方法?
Thanks.
谢谢。
回答by assylias
The few tests I can think of are:
我能想到的几个测试是:
- test hasNext on an empty collection (returns false)
- test next() on an empty collection (throws exception)
- test hasNext on a collection with one item (returns true, several times)
- test hasNext/next on a collection with one item: hasNext returns true, next returns the item, hasNext returns false, twice
- test remove on that collection: check size is 0 after
- test remove again: exception
- final test with a collection with several items, make sure the iterator goes through each item, in the correct order (if there is one)
- remove all elements from the collection: collection is now empty
- 在空集合上测试 hasNext(返回 false)
- 在空集合上测试 next()(抛出异常)
- 在包含一项的集合上测试 hasNext(多次返回 true)
- 在包含一项的集合上测试 hasNext/next:hasNext 返回 true,next 返回该项,hasNext 返回 false,两次
- 在该集合上测试删除:检查大小为 0 之后
- 再次测试删除:异常
- 对包含多个项目的集合进行最终测试,确保迭代器以正确的顺序遍历每个项目(如果有)
- 从集合中删除所有元素:集合现在是空的
You can also have a look at the tests used in openJDK.
您还可以查看openJDK 中使用的测试。
回答by piotrek
You don't.
你没有。
Guys from oracle and sun have already done that.
oracle 和 sun 的人已经这样做了。
If you create your own implementation of iterator then you have to implement AFAIR 2 methods and you have to check if they obey to the contract.
如果您创建自己的迭代器实现,则必须实现 AFAIR 2 方法,并且必须检查它们是否遵守约定。
Now that means: returning next element of underlying collection or throwing an exception and telling if there are subsequent elements. Just call those methods on your iterator and assert the result.
现在这意味着:返回底层集合的下一个元素或抛出异常并告诉是否有后续元素。只需在迭代器上调用这些方法并断言结果即可。