Reputation: 808
I want to test a method with signature int[] myMethod(int[] array, int removedElement)
as argument.
The method should remove the element if the element in in the array. As a result, the method may be able to return int[]
with array.length - 1
.
assertArrayEquals()
does not confirm if the returned array has different length.
assertNotEquals()
is not appropriate because the method may be removed wrongly more than one element.
How can I test this method?
Upvotes: 3
Views: 8863
Reputation: 36733
I'd still test using arrayAssertsEquals, just craft your inputs and expected results using new int[]{}
@Test
public void shrinksArray() {
assertArrayEquals(new int[] { 2, 3 }, remove(new int[] { 1, 2, 3 }, 1));
assertArrayEquals(new int[] { 1, 2 }, remove(new int[] { 1, 2, 3 }, 3));
assertArrayEquals(new int[] { 1, 3 }, remove(new int[] { 1, 2, 3 }, 2));
assertArrayEquals(new int[] { 1, 2, 3 }, remove(new int[] { 1, 2, 3 }, 9));
}
Or if you're crazy about single assertions per test...
private static final int[] ORIGINAL = new int[] { 1, 2, 3 };
@Test
public void removesFromBeginning() {
assertArrayEquals(new int[] { 2, 3 }, remove(ORIGINAL, 1));
}
@Test
public void removesFromEnd() {
assertArrayEquals(new int[] { 1, 2 }, remove(ORIGINAL, 3));
}
@Test
public void removesFromMiddle() {
assertArrayEquals(new int[] { 1, 3 }, remove(ORIGINAL, 2));
}
@Test
public void doesNotRemoveUnknownItem() {
assertArrayEquals(ORIGINAL, remove(ORIGINAL, 9));
}
Upvotes: 2
Reputation:
Looking through the JUnit docs, I found assertEquals(long, long)
. You should be able to do something like this:
Assert.assertEquals("The array length is not what was expected!", (long) array.length - 1, (long) modifiedArray.length);
Assuming you're saving your modified array in the modifiedArray
variable, of course.
(I have little to no experience with JUnit, so I could be totally wrong. If I am, let me know.)
Upvotes: 3
Reputation: 44448
There are two aspects to assert on:
It's true that the former will be implicitly tested with the latter, but I prefer to do that explicitly.
This makes it easy: store the length of the input and compare it with the output with assertEquals()
.
For the latter you take the input array (new[] { 5, 6 }
) and output (new[] { 5 }
) and you use assertArrayEquals()
to compare the output with the result of your method, given the input and argument 6
.
Upvotes: 2