Search code examples
javajunit

is this a good way to call Junit assertions in a common method?


I have written tests which call a method to find the missing number in a given 1 to n array. The test code is as follows:

public class MissingNumberInArrayTest {

    private int arrElements;
    private int[] arr;

    @Test
    public void mustReturnMissingNumberCase1() {
        // Given
        arrElements = 5;
        arr = new int[]{1, 2, 3, 4};

        // When & Then
        callAssertion(arr, arrElements, 5);

    }

    @Test
    public void mustReturnMissingNumberCase2() {
        // Given
        arrElements = 5;
        arr = new int[]{2, 3, 4, 5};

        // When & Then
        callAssertion(arr, arrElements, 1);

    }

    public void callAssertion(int[] arr, int arrElements, int expected) {
        // When
        int missingNumber = MissingNumberInArray.findMissingNumber(arr, arrElements);

        // Then
        Assertions.assertEquals(expected, missingNumber);
    }

}

As you can see, I have multiple cases to test and have used the assertion in common method which takes input and asserts the data. Is this a good way of writing tests?


Solution

  • This question doesn't have an exact answer (IMO), so it will probably be deleted soon.

    I wouldn't do it for simple cases like your example but if it makes your life easier, I don't see anything wrong with it. You could rename the method as assertMissingNumber and it wouldn't be that much different than usual (although the method you really want to test is in the assertion call).

    I think your specific example is perfect for parameterized tests, though.

    This is what it would look like with Junit 4:

    @RunWith( Parameterized.class )
    public class MissingNumberInArrayTest {
    
        @Parameterized.Parameters
        public static Collection<Object[]> data() {
            return Arrays.asList( new Object[][] {
                    { 5, new int[]{1, 2, 3, 4}, 5},
                    { 5, new int[]{2, 3, 4, 5}, 1}
            });
        }
    
        @Parameterized.Parameter(0)
        public int arrElements;
    
        @Parameterized.Parameter(1)
        public int[] arr;
    
        @Parameterized.Parameter(2)
        public int expected;
    
        @Test
        public void mustReturnMissingNumberCase() {
            // When
            int missingNumber = MissingNumberInArray.findMissingNumber(arr, arrElements);
    
            // Then
            assertEquals( expected, missingNumber);
        }
    }
    

    You can check on the JUnit documentation for examples with JUnit 5