jmockit / jmockit1

Advanced Java library for integration testing, mocking, faking, and code coverage
Other
465 stars 240 forks source link

equals / toString not called on superclass if called on childclass that has a mocked "sibling" class #63

Closed cm-rudolph closed 10 years ago

cm-rudolph commented 10 years ago

The following test fails, if ChildClassA is mocked (using for example @Injectable or @Mocked). If I try to debug the running test, I see that the parent equals method isn't executed. toString doesn't get executed on the parent class, too. If I remove the unused parameter or try to compare two instances of ChildClassA, everything works as expected.

import mockit.Injectable;
import mockit.integration.junit4.JMockit;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;

@RunWith(JMockit.class)
public class InheritanceTest {
    @Test
    public void testThatFails(@Injectable ChildClassA notUsed) {
        assertEquals(new ChildClassB(1), new ChildClassB(1));
    }

    @Test
    public void testThatSucceeds() {
        assertEquals(new ChildClassB(1), new ChildClassB(1));
    }

    @Test
    public void testThatSucceedsToo(@Injectable ChildClassA notUsed) {
        assertEquals(new ChildClassA(1), new ChildClassA(1));
    }

    public static class ParentClass {
        private final int id;

        public ParentClass(int id) {
            this.id = id;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof ParentClass && id == ((ParentClass) o).id;
        }

        @Override
        public int hashCode() {
            return id;
        }

        @Override
        public String toString() {
            return "id = " + id;
        }
    }

    public static class ChildClassA extends ParentClass {
        public ChildClassA(int id) {
            super(id);
        }
    }

    public static class ChildClassB extends ParentClass {
        public ChildClassB(int id) {
            super(id);
        }
    }
}

I tested using JMockit 1.11, JUnit 4.11 and Java 8u20.

cm-rudolph commented 10 years ago

A simple workaround for now is to add @Injectable ChildClassB workaround as parameter to testThatFails' signature.