Mock private field being initialized by OSGI Felix container

独自空忆成欢 提交于 2019-12-11 09:48:26

问题


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


回答1:


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 */);
    }
} 


来源:https://stackoverflow.com/questions/44839906/mock-private-field-being-initialized-by-osgi-felix-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!