Class ServiceHelper

  • All Implemented Interfaces:
    Closeable, AutoCloseable, org.junit.rules.TestRule

    public class ServiceHelper
    extends Object
    implements org.junit.rules.TestRule, Closeable
    A JUnit 4 TestRule for running tests against an apollo service. It is built around the AppInit setup mechanism and can be used to start a service configured in a way appropriate for the test scenario.

    See ServiceHelperExtension when testing Apollo services using JUnit 5.

    Typical usage would use create(AppInit, String) together with a Rule annotation. Further configuration like config key overrides, running domain and additional program arguments can be set up using conf(String, String), domain(String) and args(String...) respectively.

    Requests can be sent to the running application using any of request(com.spotify.apollo.Request) methods.

    Example usage for testing a route provider

    
     @RunWith(MockitoJUnitRunner.class)
     class MyServiceTest {
    
      @Rule
       public ServiceHelper serviceHelper = ServiceHelper.create(this::appInit, "my-service")
           .conf("some.key", "some-value")
           .args("-v")
           .startTimeoutSeconds(30);
    
      @Mock
       SomeObject someObject;
    
       void appInit(Environment environment) {
         // Implements resource "/endpoint" using someObject
         RouteProvider endpointResource = new EndpointResource(someObject);
         environment.routingEngine()
             .registerAutoRoutes(endpointResource);
       }
    
      @Test
       public void testRequest() throws Exception {
         when(someObject.thatDoesThings()).thenReturn("a test string");
    
         String response = Futures.getUnchecked(serviceHelper.request("GET", "/endpoint"))
             .getPayloads().get(0).toStringUtf8();
    
         assertThat(response, is("a test string"));
       }
     }
     

    Example usage for system or acceptance tests

    
     @RunWith(MockitoJUnitRunner.class)
     class MyServiceTest {
    
       // Implements AppInit
       MyService myService = new MyService();
    
      @Rule
       public ServiceHelper serviceHelper = ServiceHelper.create(myService, "my-service")
           .conf("some.key", "some-value")
           .args("-v")
           .startTimeoutSeconds(30);
    
      @Test
       public void testRequest() throws Exception {
         String response = Futures.getUnchecked(serviceHelper.request("GET", "/ping"))
             .getPayloads().get(0).toStringUtf8();
    
         assertThat(response, is("pong"));
       }
     }
     

    Faking outgoing request responses

    The service helper instance will contain a StubClient that can be accessed through stubClient(). This can be used to setup mocked replies on outgoing requests. Requests made by the application will first try to match against requests set up in the StubClient. But if none is found the request will be delegated to the underlying client that is normally available to the application through Environment.client() or RequestContext.requestScopedClient().

    See StubClient for more docs on how to set up mocked request replies.

    See Also:
    ServiceHelperExtension
    • Field Detail

      • NO_ARGS

        public static final String[] NO_ARGS
    • Method Detail

      • create

        public static ServiceHelper create​(com.spotify.apollo.AppInit appInit,
                                           String serviceName)
        Creates a ServiceHelper using the given AppInit and service name.
        Parameters:
        appInit - The init function for the test setup
        serviceName - The service name for looking up config
        Returns:
        A ServiceHelper to be used with a JUnit Rule
      • create

        public static ServiceHelper create​(com.spotify.apollo.AppInit appInit,
                                           String serviceName,
                                           StubClient stubClient)
        Creates a ServiceHelper using the given AppInit, service name and stub client. Use, for instance, when you want to configure the thread count of the stub client.
        Parameters:
        appInit - The init function for the test setup
        serviceName - The service name for looking up config
        stubClient - The stub client to use
        Returns:
        A ServiceHelper to be used with a JUnit Rule
      • domain

        public ServiceHelper domain​(String domain)
        Run the service in the given domain. This will set the "apollo.backend" config key which is also available through Environment.domain().
        Parameters:
        domain - The domain to use
        Returns:
        This ServiceHelper instance
      • disableMetaApi

        public ServiceHelper disableMetaApi()
        Don't set up /_meta/* routes for the application.
        Returns:
        This ServiceHelper instance
      • args

        public ServiceHelper args​(String... args)
        Run the service with the given program arguments.
        Parameters:
        args - The program arguments to use
        Returns:
        This ServiceHelper instance
      • conf

        public ServiceHelper conf​(String key,
                                  String value)
        Run the service with the key/value pair defined in the loaded configuration. The key/values defined through this method will be overlayed over any existing config loaded through the given service name when creating this ServiceHelper.
        Parameters:
        key - The key to define
        value - The value to associate with the key
        Returns:
        This ServiceHelper instance
      • conf

        public ServiceHelper conf​(String key,
                                  Object value)
        Run the service with the key/value pair defined in the loaded configuration. The key/values defined through this method will be overlayed over any existing config loaded through the given service name when creating this ServiceHelper.
        Parameters:
        key - The key to define
        value - The value for the configuration. It can be any accepted type as described by this method's documentation: ConfigValueFactory.fromAnyRef( java.lang.Object, java.lang.String)
        Returns:
        This ServiceHelper instance
      • resetConf

        public ServiceHelper resetConf​(String key)
        Reset a key in the configuration
        Parameters:
        key - The path to unset
        Returns:
        This ServiceHelper instance
      • getInstance

        public com.spotify.apollo.core.Service.Instance getInstance()
        Get the running service instance.
        Returns:
        the service instance
      • forwardingNonStubbedRequests

        public ServiceHelper forwardingNonStubbedRequests​(boolean forward)
        Determines whether to forward requests for which nothing has been stubbed. The default is true. If false, requests that don't match stubs will fail.
        Parameters:
        forward - whether to enable forwarding
      • startTimeoutSeconds

        public ServiceHelper startTimeoutSeconds​(int timeoutSeconds)
        Set the time to wait for the service to start before giving up. The default value is 5.
      • withModule

        public ServiceHelper withModule​(com.spotify.apollo.module.ApolloModule module)
      • scheme

        public ServiceHelper scheme​(String scheme)
        Set the scheme to be used for relative request uris on this ServiceHelper instance. When request() methods are called with a uri without scheme, scheme://serviceName is prepended
        Parameters:
        scheme - The scheme to be used for relative request uris (without "://")
        Returns:
        This ServiceHelper instance
      • stubClient

        public StubClient stubClient()
        A StubClient that can be used to mock outgoing application request responses.
        Returns:
        the stub client for this service helper instance
      • serviceClient

        public com.spotify.apollo.Client serviceClient()
        Get a Client that allows to make requests to the service created by this helper
        Returns:
        A client that can resolve requests to this service
      • request

        public CompletionStage<com.spotify.apollo.Response<okio.ByteString>> request​(com.spotify.apollo.Request request)
        Make a call to the running application and return a CompletionStage of the response.
        Parameters:
        request - The request to send to the application
        Returns:
        A future of the response
      • request

        public CompletionStage<com.spotify.apollo.Response<okio.ByteString>> request​(String method,
                                                                                     String uri)
        Makes a call on the given uri. The uri can be an application relative path such as "/ping" or a full path like {@link "http:///ping"}.
        Parameters:
        method - The method of the call
        uri - The uri of the call
        Returns:
        A future of the response
      • request

        public CompletionStage<com.spotify.apollo.Response<okio.ByteString>> request​(String method,
                                                                                     URI uri)
        Makes a call on the given uri. The uri can be an application relative path such as "/ping" or a full path like {@link "http:///ping"}.
        Parameters:
        method - The method of the call
        uri - The uri of the call
        Returns:
        A future of the response
      • request

        public CompletionStage<com.spotify.apollo.Response<okio.ByteString>> request​(String method,
                                                                                     String uri,
                                                                                     okio.ByteString payload)
        Makes a call on the given uri. The uri can be an application relative path such as "/ping" or a full path like {@link "http:///ping"}.
        Parameters:
        method - The method of the call
        uri - The uri of the call
        payload - A payload body
        Returns:
        A future of the response
      • request

        public CompletionStage<com.spotify.apollo.Response<okio.ByteString>> request​(String method,
                                                                                     URI uri,
                                                                                     okio.ByteString payload)
        Makes a call on the given uri. The uri can be an application relative path such as "/ping" or a full path like {@link "http:///ping"}.
        Parameters:
        method - The method of the call
        uri - The uri of the call
        payload - A payload body
        Returns:
        A future of the response
      • apply

        public org.junit.runners.model.Statement apply​(org.junit.runners.model.Statement base,
                                                       org.junit.runner.Description description)
        Specified by:
        apply in interface org.junit.rules.TestRule