Mock private field being initialized by OSGI Felix

2019-07-27 08:39发布

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条回答
家丑人穷心不美
2楼-- · 2019-07-27 08:59

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 */);
    }
} 
查看更多
登录 后发表回答