如何在JUnit测试中测试Collection中元素的排序? [英] How to test the ordering of elements in a Collection in JUnit test?

查看:182
本文介绍了如何在JUnit测试中测试Collection中元素的排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JUnit测试来验证我在Java中的集合的排序算法。如果我将B,C,A输入到集合中并希望对其进行排序(例如按字母顺序排列),使用JUnit对此进行测试的正确方法是什么?

I want to verify my ordering algorithm of a collection in Java with JUnit tests. If I input "B","C","A" into a collection and want it sorted (alphabetically for example), what is the proper way to test this with JUnit ?

我实现了Comparable接口,并希望确保我的排序正常工作。

I implemented the Comparable interface and want to make sure my sorting is working.

我想这个问题可以扩展到Java或JUnit以外的任何语言的一般测试。

I suppose this question could be broaden beyond Java or JUnit to general testing in any language.

推荐答案

我会使用期望顺序中的值创建另一个集合,然后只需检查结果匹配。

I would create another collection with the values in the expected order, and then just check that the results match.

但说实话,如果您只是想检查 IComparable 的执行情况并且某种排序算法,我只是对调用 compareTo 的结果做出断言。编写测试会更简单,而更多更容易理解任何失败。

But to be honest, if you're just trying to check your implementation of IComparable and not some sort algorithm, I would just make assertions about the results of calling compareTo. It'll be simpler to write the tests and much simpler to understand any failures.

(如果排序测试失败,那只是意味着许多比较中的一个做错了。它无法帮助你解决哪个比较做错了。)

(If a sorting test fails, that would just mean that one of the many comparisons did the wrong thing. It wouldn't help you work out which comparison did the wrong thing.)

这篇关于如何在JUnit测试中测试Collection中元素的排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆