Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent behaviour of @InjectMocks annotation #2826

Open
el-hopaness-romtic opened this issue Dec 18, 2022 · 1 comment
Open

Inconsistent behaviour of @InjectMocks annotation #2826

el-hopaness-romtic opened this issue Dec 18, 2022 · 1 comment

Comments

@el-hopaness-romtic
Copy link

el-hopaness-romtic commented Dec 18, 2022

Consider classes A and B

public class A {
    String call() {
        return null;
    }
}
public class B extends A {
}

And class C, contructor of which uses inctances of both A and B

public class C {
    private final A a;
    private final B b;

    C(A a, B b) {
        this.a = a;
        this.b = b;
    }

    public void callFields() {
        System.out.println("A " + a.call());
        System.out.println("B " + b.call());
    }
}

In that case following test does not behave consistently

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class MockitoTest {
    @Mock
    A a;
    @Mock
    B b;
    @InjectMocks
    C c;

    @Test
    void test() {
        when(a.call()).thenReturn("A");
        when(b.call()).thenReturn("B");
        c.callFields();
    }
}

image
image

org.junit.jupiter:junit-jupiter:5.9.1
org.mockito:mockito-junit-jupiter:4.8.1
openjdk version "17.0.3" 2022-04-19 LTS

@HermitDede
Copy link

This issue caused me at least 1-2 hours to figure out. There was no clear explanation or warning for the root cause. It was behaving differently on each context. I came here to post this issue, but looks like this has been ongoing for 1 year 😞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants