All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.somospnt.test.server.MockRestServiceServerBuilder Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package com.somospnt.test.server;

import java.util.ArrayList;
import java.util.List;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

/**
 * A class that creates a sequence of REST operations to be mocked.
 *
 * Example code:
 *
 * 
 * {@code
 * MockRestServiceServer mockRestServiceServer = MockRestServiceServerBuilder
 *               .withRestTemplate(restTemplate)
 *               .withMockOperation(new MockRestGetOperationImpl("URL1", HttpStatus.ACCEPTED))
 *               .withMockOperation(new MockRestGetOperationImpl("URL2", HttpStatus.CREATED))
 *               .build();
 *
 * // ... do some request to restTemplate
 *
 * mockRestServiceServer.verify();
 * }
 * 
* * @author SomosPNT */ public class MockRestServiceServerBuilder { /** * The mock server to use. */ private final MockRestServiceServer mockServer; /** * List of RestOperation to mock. */ private final List mockRestOperationList; private MockRestServiceServerBuilder(RestTemplate restTemplate) { mockServer = MockRestServiceServer.createServer(restTemplate); mockRestOperationList = new ArrayList<>(); } /** * Generate an instance of MockRestServiceServerBuilder and starts the * mockServer. * * @param restTemplate the RestTemplate to use for creating the mockServer. */ public static MockRestServiceServerBuilder withRestTemplate(RestTemplate restTemplate) { return new MockRestServiceServerBuilder(restTemplate); } /** * Adds an operation to mock server in sequence * * @param mockRestOperation the AbstractMockRestOperation to mock. */ public MockRestServiceServerBuilder withMockOperation(AbstractMockRestOperation mockRestOperation) { Assert.notNull(mockRestOperation, "mockRestOperation must not be null."); mockRestOperationList.add(mockRestOperation); return this; } /** * Mock of all operation added in sequence * * @return the instance of MockRestServiceServerBuilder with the * MockRestServiceServer. */ public MockRestServiceServer build() { if (mockRestOperationList.isEmpty()) { throw new IllegalStateException("mockRestOperationList must not be empty."); } mockRestOperationList.forEach(mockOperation -> mockOperation.mock(mockServer)); return mockServer; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy