Package net.jadler

Class JadlerMocker

  • All Implemented Interfaces:
    Mocker, RequestManager, StubHttpServerManager, Stubber

    public class JadlerMocker
    extends Object
    implements StubHttpServerManager, Stubber, RequestManager, Mocker

    This class represents the very hearth of the Jadler library. It acts as a great Stubber providing a way to create new http stubs, StubHttpServerManager allowing the client to manage the state of the underlying stub http server and RequestManager providing stub response definitions according to a given http request.

    An underlying stub http server instance is registered to an instance of this class during the instantiation.

    Normally you shouldn't create instances of this on your own, use the Jadler facade instead. However, if more http stub servers are needed in one execution thread (for example two http stub servers listening on different ports) have no fear, go ahead and create two or more instances directly.

    This class is stateful and thread-safe.

    • Constructor Detail

      • JadlerMocker

        public JadlerMocker​(StubHttpServer server)
        Creates new JadlerMocker instance bound to the given http stub server.
        Parameters:
        server - stub http server instance this mocker should use
    • Method Detail

      • isStarted

        public boolean isStarted()
        Specified by:
        isStarted in interface StubHttpServerManager
        Returns:
        true, if the stub server has already been started, otherwise false
      • addDefaultHeader

        public void addDefaultHeader​(String name,
                                     String value)
        Adds a default header to be added to every stub http response.
        Parameters:
        name - header name (cannot be empty)
        value - header value (cannot be null)
      • setDefaultStatus

        public void setDefaultStatus​(int defaultStatus)
        Defines a default status to be returned in every stub http response (if not redefined in the particular stub rule)
        Parameters:
        defaultStatus - status to be returned in every stub http response. Must be at least 0.
      • setDefaultEncoding

        public void setDefaultEncoding​(Charset defaultEncoding)
        Defines default charset of every stub http response (if not redefined in the particular stub)
        Parameters:
        defaultEncoding - default encoding of every stub http response
      • onRequest

        public RequestStubbing onRequest()
        Starts new stubbing (definition of a WHEN-THEN rule).
        Specified by:
        onRequest in interface Stubber
        Returns:
        stubbing object to continue the stubbing
      • provideStubResponseFor

        public StubResponse provideStubResponseFor​(Request request)
        Returns a stub response for the given request. The request is recorded for further mocking (verifying).
        Specified by:
        provideStubResponseFor in interface RequestManager
        Parameters:
        request - http request to return a stub response for
        Returns:
        definition of a stub response to be returned by the stub http server (never returns null)
      • verifyThatRequest

        public Verifying verifyThatRequest()
        Starts new verification process.
        Specified by:
        verifyThatRequest in interface Mocker
        Returns:
        verifying object to continue the ongoing verifying
      • evaluateVerification

        public void evaluateVerification​(Collection<org.hamcrest.Matcher<? super Request>> requestPredicates,
                                         org.hamcrest.Matcher<Integer> nrRequestsPredicate)
        Description copied from interface: RequestManager
        Verifies whether the number of received http requests fitting the given predicates is as expected. Basically at first this operation computes the exact number of http requests received so far fitting the given predicates and then verifies whether the number is as expected. If not a VerificationException is thrown and the exact reason is logged on the INFO level.
        Specified by:
        evaluateVerification in interface RequestManager
        Parameters:
        requestPredicates - predicates about the http requests received so far (cannot be null, can be empty however)
        nrRequestsPredicate - a predicate about the number of http requests received so far which fit the given request predicates (cannot be null)
      • reset

        public void reset()

        Resets this mocker instance so it can be reused. This method clears all previously created stubs as well as stored received requests (for mocking purpose, see RequestManager.numberOfRequestsMatching(java.util.Collection)). Once this method has been called new stubs can be created again using onRequest().

        Please note that calling this method in a test body always signalizes a poorly written test with a problem with the granularity. In this case consider writing more fine grained tests instead of using this method.

        While the standard Jadler lifecycle consists of creating new instance of this class and starting the underlying stub server (using start()) in the before section of a test and stopping the server (using close()) in the after section, in some specific scenarios it could be useful to reuse one instance of this class in all tests instead.

        When more than just one instance of this class is used in a test suite (for mocking more http servers) it could take some time to start all underlying stub servers before and stop these after every test method. This is a typical use case this method might come to help.

        Here's an example code using jUnit which demonstrates usage of this method in a test lifecycle:

         public class JadlerResetIntegrationTest {
             private static final JadlerMocker mocker = new JadlerMocker(new JettyStubHttpServer());
        
             @BeforeClass
             public static void beforeTests() {
                 mocker.start();
             }
        
             @AfterClass
             public static void afterTests() {
                 mocker.close();
             }
        
             @After
             public void reset() {
                 mocker.reset();
             }
        
             @Test
             public void test1() {
                 mocker.onRequest().respond().withStatus(201);
        
                 //do an http request here, 201 should be returned from the stub server
        
                 verifyThatRequest().receivedOnce();
             }
        
             @Test
             public void test2() {
                 mocker.onRequest().respond().withStatus(400);
        
                 //do an http request here, 400 should be returned from the stub server
        
                 verifyThatRequest().receivedOnce();
             }
         }
         
      • setRecordRequests

        public void setRecordRequests​(boolean recordRequests)

        By default Jadler records all incoming requests (including their bodies) so it can provide mocking (verification) features defined in Mocker.

        In some very specific corner cases this implementation of mocking can cause troubles. For example imagine a long running performance test using Jadler for stubbing some remote http service. Since such a test can issue thousands or even millions of requests the memory consumption probably would affect the test results (either by a performance slowdown or even crashes). In this specific scenarios you should consider disabling the incoming requests recording using this method.

        When disabled calling Mocker.verifyThatRequest() will result in IllegalStateException

        Please note you should ignore this option almost every time you use Jadler unless you are really convinced about it. Because premature optimization is the root of all evil, you know.

        Parameters:
        recordRequests - true for enabling http requests recording, false for disabling it