Question

Public class Person {
    private Skill[] skills;

    public Skill[] getSkills() {
        return skills;
    }

    public void setSkills(Skill[] s) {
        if (s!= null) {
            skills = new Skill[s.length];

            for (int i = 0; i < s.length; i++) {
                skills[i] = s[i];
            }
        }
    }
}
}

Assume there is a class skill. The problem is there is a test case in Junit that tests the method setSkill ugiving s = the skills array itself. This test case returns Assertion error telling me The returned skill array should be the same knowing that when I change the getSkill to be giving both arrays same reference the test case passes.

Can anyone help me with that please? how do I copy the elements not the reference? and why does the test case fails?

the test case is :

@Test(timeout = 1000) 
public void testGetSkills() { 
    instance.setSkills(skills); 
    assertSame("The returned skill array should be the same", instance.getSkills(), skills); 
}
Was it helpful?

Solution

You mention that your test case uses assertSame. This looks for reference equality, and requires that a == b.

Your code creates a copy. A copy will never have reference equality to the original. In some classes that override the Object method Equals it may be true that assertEquals will pass. In the case of an array, try using assertArrayEquals.

For example this test should pass:

@Test
public void assertArrayEqualsTest() throws Exception {
  assertArrayEquals(new int[]{1, 2, 3}, new int[]{1, 2, 3});
}

But this test will fail:

@Test
public void assertSameTest() throws Exception {
  assertSame(new int[]{1, 2, 3}, new int[]{1, 2, 3});
}

You should be clear on why this is.

OTHER TIPS

You are not copying the elements, you simply create another array pointing to the same elements. So if your test case later on modifies the array skills, you will also modify the original array s. I guess this is what causes the assertion to fail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top