user3738926
user3738926

Reputation: 1268

junit how would I assert that my method returns a specific array

I have a method that returns the array Sighting[]. In my unit test, there should be one element (element1) at index[0].

My question is, how do I build my statement to reflect this ? I need to assert that the array returned by my getMostOfSpecies method contains element1 at the first index value.

my (failing) test looks like this

@Test
public void getMostOfSpeciesTest()
{
    try {
        birdList1.remember(sighting5);
        birdList1.remember(sighting6);
        birdList1.remember(sighting7);
        birdList1.remember(sighting8);
        assertEquals(birdList1.getMostOfSpecies("SOBI"), Sighting[???what to put here???]);
    }
    catch (Exception e) {
        fail("Failed" + e.getMessage());
    }
}

Upvotes: 0

Views: 2683

Answers (1)

André Diermann
André Diermann

Reputation: 2783

Have you tried Arrays.equals() [1]? Make sure you override the equals()-method of your Sighting class as well.

assertTrue( Arrays.equals(birdList1.getMostOfSpecies("SOBI"), yourSightingArray);

[1] https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

Edit:

If you need to check if the array contains one particular object you might be interested in Arrays.binarySearch() [2] or in Arrays.asList() in conjunction with List's contains()-method. So your assert-statement should look like

assertTrue( Arrays.binarySearch(birdList1.getMostOfSpecies("SOBI"), theElementYouExpect) >= 0);

[2] https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(java.lang.Object[],%20java.lang.Object)

Upvotes: 2

Related Questions