Search code examples
javamockitoapache-felixosgi-bundle

Mock private field being initialized by OSGI Felix container


I'm trying to mock a private field in my class which is being initialized by OSGI container in which my app is running. I'm putting a sample code for reference, any clue on this please:

import org.apache.felix.scr.annotations.*
@Component (name = "MyServiceImpl ", ds = true, immediate = true)
@Service
public class MyServiceImpl extends MyBasee implements MyService {

    @Reference (name = "MyOtherService", bind = "bind", unbind = "unbind", policy = ReferencePolicy.STATIC)
    private MyOtherService myServiceRegistryConsumer;
}

Here I'm trying to mock private field MyOtherService myServiceRegistryConsumer


Solution

  • With Mockito you can mock and inject fields using the @InjectMocksannotation.

    @RunWith(MockitoJUnitRunner.class)
    public class AppTest {
    
        @Mock
        private MyOtherService myServiceRegistryConsumer;
    
        @InjectMocks
        private MyServiceImpl myServiceImpl;
    
        @Test
        public void testSomething() {
            // e.g. define behavior for the injected field
            when(myServiceRegistryConsumer.methodA()).thenReturn(/* mocked return value */);
        }
    }