H.Houssein
H.Houssein

Reputation: 23

assertEquals(Object[], Object[]) in JUnit?

So I was going through the JUnit 4.0 testing and I test object (Stick) arrays if they are equal, which they are, but I get a failure test.

Stick class:

 public class Stick {
        private char stick;

        public Stick() {
            stick = 'I';
    }

The Game class - where I initialize the array of Stick:

public class Game {
private Stick[] sticks;

public Stick[] StartNewGame() {
    counter = 1;
    sticks = new Stick[22];

    for(int i = 0; i<sticks.length; i++) {
        Stick a_stick = new Stick();
        sticks[i] = a_stick;
    }
    return sticks;
}

The test code:

@Test
    public void ShouldStartAGame() {
        Stick[] sticks = new Stick[22];
        for(int i = 0; i<sticks.length; i++) {
            Stick a_stick = new Stick();
            sticks[i] = a_stick;
        }
        assertArrayEquals(sticks, game.StartNewGame());

    }

Upvotes: 0

Views: 655

Answers (1)

Gavin
Gavin

Reputation: 1767

I think, this is due to the lack of an equals method on Stick, so equals is comparing the memory address of the Stick[] elements and finding them to be different.

Override the default equals (and hashcode) methods in Stick.

Also the test violates the DRY principle, as you are repeating your implementing code in the test, if you duplicate a mistake from the implementation into the test using cut and paste no unit test in the world will find a mistake.

Upvotes: 1

Related Questions