模拟私有字段由OSGI Felix容器初始化

时间:2017-06-30 06:24:25

标签: java mockito apache-felix osgi-bundle

我正在尝试在我的类中模拟一个私有字段,该字段由运行我的应用程序的OSGI容器初始化。我正在提供一个示例代码供参考,请提供任何线索:

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;
}

我在这里试图模仿私人字段MyOtherService myServiceRegistryConsumer

1 个答案:

答案 0 :(得分:2)

使用Mockito,您可以使用@InjectMocks注释来模拟和注入字段。

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