Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we test if an array returns with different length?

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?

like image 948
Photon Point Avatar asked Feb 01 '26 16:02

Photon Point


2 Answers

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.)

There are two aspects to assert on:

  • The length of the array
  • The content of the array

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.

like image 28
Jeroen Vannevel Avatar answered Feb 04 '26 06:02

Jeroen Vannevel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!