I have a unit test that needs to compare two arrays but it shouldn't care about the order of the arrays. I didn't see anything in the Test:Unit docs that provided this so I wrote my own. I really don't want to use this code if I don't have to (want to avoid Not Invented Here syndrome).
If you can give me some feedback on the following points it would be a huge help, thanks!
- Should I even use this? Is there a built-in Test:Unit assertion I can use?
- I've refactored this as much as I can but any further improvements are encouraged and welcome.
- I've included my tests for this custom assertion, can you see any cases that I may be missing?
Here is the custom assertion:
def assert_have_same_items(expected, actual, message = nil)
full_message = build_message(message, "<?> was expected to contain the same collection of items as \n<?> but did not.\n", actual, expected)
test = expected | actual
assert_equal expected.size, actual.size, full_message
assert_equal expected.size, test.size, full_message
end
And the tests:
test "assert_have_same_items with two arrays with same items in same order reports success" do
assert_have_same_items [1,2,3], [1,2,3]
end
test "assert_have_same_items with two arrays with same items in different order reports success" do
assert_have_same_items [1,2,3], [2,1,3]
end
test "assert_have_same_items with actual missing an item, reports failure" do
assert_should_fail do
assert_have_same_items [1,2,3], [2,1]
end
end
test "assert_have_same_items with actual having more items, reports failure" do
assert_should_fail do
assert_have_same_items [1,2,3], [2,1,3,4,5,6]
end
end
test "assert_have_same_items with actual having duplicates, reports failure" do
assert_should_fail do
assert_have_same_items [1,2,3], [2,1,3,2,1,3]
end
end
test "assert_have_same_items with actual having duplicates and expected having same number of items, reports failure" do
assert_should_fail do
assert_have_same_items [1,2,3,4,5,6], [2,1,3,2,1,3]
end
end
protected
def assert_should_fail
begin
yield if block_given?
flunk "Expected failure but assertion reported success"
rescue Test::Unit::AssertionFailedError
assert true
end
end