1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to mock a ServiceBuilder using Mockito

Discussão em 'StackOverflow' iniciado por Stack, Fevereiro 23, 2021.

  1. Stack

    Stack Membro Participativo

    I'm trying to mock a org.jboss.msc.service.ServiceBuilderfor a simple ServiceActivator class that I have but my test failes at the ServiceBuilder<?> builder = ....

    What's the best way to mock this object so my tests can get past the point below?

    ServiceActivator

    import org.jboss.msc.service.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.wildfly.clustering.service.ActiveServiceSupplier;
    import org.wildfly.clustering.singleton.SingletonDefaultRequirement;
    import org.wildfly.clustering.singleton.service.SingletonPolicy;

    import java.util.function.Supplier;
    /**
    * Service activator that installs the TimerService as
    * a clustered singleton service during deployment.
    */
    public class TimerServiceActivator implements ServiceActivator {

    private static final Logger logger = LoggerFactory.getLogger(TimerServiceActivator.class);

    @Override
    public void activate(ServiceActivatorContext context) throws ServiceRegistryException {

    logger.info("timer will be installed");
    try {
    TimerService service = new TimerService();
    Supplier<SingletonPolicy> policy = new ActiveServiceSupplier<>(context.getServiceRegistry(), ServiceName.parse(SingletonDefaultRequirement.POLICY.getName()));
    //Needs to be return a mocked instance of ServiceBuilder
    ServiceBuilder<?> builder = policy.get().createSingletonServiceConfigurator(TimerService.SINGLETON_SERVICE_NAME).build(context.getServiceTarget());
    ////////////////
    builder.setInstance(service).install();
    logger.info("timer installed!");
    } catch (Exception ie) {
    throw new ServiceRegistryException("Error activating timer", ie);
    }
    }
    }


    Test

    public class TimerServiceActivatorTest {


    @Test
    public void testActivate(@Mocked ServiceActivatorContext context) {
    SingletonPolicy policy = Mockito.mock(SingletonPolicy.class);;
    ServiceBuilder<?> builder = Mockito.mock(ServiceBuilder.class);
    ServiceConfigurator serviceConfigurator = Mockito.mock(ServiceConfigurator.class);
    doNothing().when(builder.install());
    activator.activate(context);
    }
    }

    Continue reading...

Compartilhe esta Página