Export to GitHub

mockito - issue #422

Constructor injection with @InjectMocks is not working properly when injecting multiple mocks of the same type


Posted on Feb 16, 2013 by Massive Lion

The problem?

Constructor injection with @InjectMocks is not working properly when injecting multiple mocks of the same type. Always single instance of given type is used.

What steps will reproduce the problem?

@RunWith(MockitoJUnitRunner.class) public class ConsolePrinterTest {

@Mock
PrintStream outStream;

@Mock
PrintStream errStream;

@InjectMocks
ConsolePrinter classUnderTest;

@Test
public void testPrinting() {

    classUnderTest.println("test msg");
    verify(outStream).println("test msg");
}

public static class ConsolePrinter {

    private final PrintStream out;
    private final PrintStream err;

    public ConsolePrinter(final PrintStream outStream, final PrintStream errStream) {
        this.out = outStream;
        this.err = errStream;
    }

    public void println(final String str) {
        out.println(str);
    }

    public void printlnError(final String str) {
        err.println(str);
    }

}

}

What is the expected output? What do you see instead?

If properly injected, the test should always be green. Instead, it is sometimes red and sometimes green, depending on which mock was used as both of contructor's arguments.

What version of the product are you using? On what operating system? mockito 1.9.5; Java 1.7.0_13; Linux 3.6.11

Comment #1

Posted on Mar 14, 2013 by Happy Horse

Hi,

You can use the mock name annotation attribute, when there is two Object of the same type. Otherwise it is not possible to detect automagically the right mocks for the right properties.

Cheers, Brice

Comment #2

Posted on Apr 29, 2013 by Happy Horse

(No comment was entered for this change.)

Status: WontFix

Labels:
Type-Defect Priority-Medium Injection