How to unit test OSGi service with ReferencePolicy=DYNAMIC using AEMContext
Hi,
I have an OSGi service (MyService) that is referencing a list of OSGi services implementing the same interface (SecondService). Debugging this code with AEM 6.5.17.0 is properly injecting all the OSGi services (serviceList has multiple objects), but when I try to replicate that in my unit test using AEMContext.registerService() to inject multiple OSGi services, I see that the reference variable is not getting injected properly. What am I doing wrong?
Here is a sample code for the MyService where the serviceList is getting injected properly on my local AEM instance.
package com.mypackage;
import org.osgi.service.component.annotations.*;
import java.util.*;
@Component(service = MyService.class,immediate = true)
public class MyServiceImpl implements MyService
{
@3214626(service = SecondService.class,
cardinality = ReferenceCardinality.MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
bind = "bindMethod",
unbind = "unbindMethod")
private volatile List<SecondService> serviceList;
protected void bindMethod(){ //DO SOMETHING }
protected void unbindMethod(){ //DO SOMETHING }
}
And the sample code for the unit tests that doesn't inject serviceList properly.
package com.mypackage;
import io.wcm.testing.mock.aem.junit.AemContext;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
@Rule
public final AemContext context = new AemContext(ResourceResolverType.RESOURCERESOLVER_MOCK);
@Mock
SecondService s1;
@Mock
SecondService s2;
@2785667
public void sampleTest(){
context.registerService(SecondService.class, s1);
context.registerService(SecondService.class, s2);
MyService service = context.registerInjectActivateService(new MyServiceImpl());
}
}
In both cases (local debug and unit test), I am debugging the MyService.bindMethod() to check whether the serviceList is injected or not.
Regards,
Raj