kokalsuhas / mockito

Automatically exported from code.google.com/p/mockito
0 stars 0 forks source link

Mixing constructor and field injection doesn't work #433

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
What steps will reproduce the problem?

public class MixedMockInjectionTest
{
    @InjectMocks
    private AClass aClass;

    @Mock
    List fieldMock;

    @Mock
    Map constructorMock;

    @Test
    public void testMixedInjection()
    {
        MockitoAnnotations.initMocks(this);
        assertSame(constructorMock, aClass.constructorDependency);
        assertSame(fieldMock, aClass.fieldDependency);
    }

    public static class AClass
    {
        final Map constructorDependency;
        List fieldDependency;

        public AClass(final Map constructorDependency) {
            this.constructorDependency = constructorDependency;
        }

    }
}

What is the expected output? What do you see instead?
java.lang.AssertionError: expected same:<fieldMock> was not:<null>

What version of the product are you using? On what operating system?
1.9.5

Original issue reported on code.google.com by kan....@gmail.com on 23 May 2013 at 10:41

GoogleCodeExporter commented 8 years ago
Hi,

This is the expected behavior, as the injection is "automagical", Mockito 
cannot infer what is safe to inject or not after the constructor injection 
happened, so it is better to respect the work done by the constructor when CI 
happen.

Aside of that it seems wrong design-wise to have constructor injection plus 
setter injection (regardless of mockito). And it's even better to make this bad 
design appear in the test, so we are more enclined to fix it. It's already 
arguable to use or not the injection feature of mockito because you don't 
always feel the pain of injecting collaborators.

That's the motivation behind this behavior, though I think this should be 
better documented in the Javadoc

Cheers,
Brice

Original comment by brice.du...@gmail.com on 23 May 2013 at 5:10