org.springframework.test.web.client.MockRestServiceServer Java Examples

The following examples show how to use org.springframework.test.web.client.MockRestServiceServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserManagementServiceTest.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
private void mockRetrieveUserServer(MockRestServiceServer server) {
    server.expect(ExpectedCount.manyTimes(), requestTo(String.format("http://%s/auth/v1/users", this.gatewayUrl)))
            .andExpect(method(HttpMethod.GET))
            .andExpect(header("Authorization", TOKEN))
            .andRespond(withSuccess(String.format("{\n" +
                    "  \"status\": \"OK\",\n" +
                    "  \"message\": \"success\",\n" +
                    "  \"data\": [\n" +
                    "    {\n" +
                    "      \"createdBy\": null,\n" +
                    "      \"updatedBy\": null,\n" +
                    "      \"createdTime\": \"2019-12-04T06:34:06.000+0000\",\n" +
                    "      \"updatedTime\": null,\n" +
                    "      \"id\": 1,\n" +
                    "      \"username\": \"%s\",\n" +
                    "      \"password\": \"%s\",\n" +
                    "      \"active\": true,\n" +
                    "      \"blocked\": null\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}", USERNAME, AS_RETURN_PASSWORD), MediaType.APPLICATION_JSON));

}
 
Example #2
Source File: RequestUriTest.java    From riptide with MIT License 6 votes vote down vote up
@Override
public void execute(final String baseUrl, final UrlResolution resolution, @Nullable final String uri,
        final HttpMethod method, @Nonnull final Consumer<Http> tester) {

    final MockSetup setup = new MockSetup(baseUrl);
    final Http unit = setup.getHttpBuilder().urlResolution(resolution).build();
    final MockRestServiceServer server = setup.getServer();

    server.expect(requestTo(requestUri))
            .andExpect(method(method))
            .andRespond(withSuccess());

    tester.accept(unit);
    server.verify();

}
 
Example #3
Source File: ResourceServerTokenRelayAutoConfigurationTests.java    From spring-cloud-security with Apache License 2.0 6 votes vote down vote up
@Test
public void clientConfigured() throws Exception {
	this.context = new SpringApplicationBuilder(ClientConfiguration.class)
			.properties("spring.config.name=test", "server.port=0",
					"spring.cloud.gateway.enabled=false",
					"security.oauth2.resource.userInfoUri:https://example.com",
					"security.oauth2.client.clientId=foo")
			.run();
	RequestContextHolder.setRequestAttributes(
			new ServletRequestAttributes(new MockHttpServletRequest()));
	OAuth2ClientContext client = this.context.getBean(OAuth2ClientContext.class);
	assertThat(client.getAccessToken()).isNull();
	UserInfoTokenServices services = context.getBean(UserInfoTokenServices.class);
	OAuth2RestTemplate template = (OAuth2RestTemplate) ReflectionTestUtils
			.getField(services, "restTemplate");
	MockRestServiceServer server = MockRestServiceServer.createServer(template);
	server.expect(requestTo("https://example.com"))
			.andRespond(withSuccess("{\"id\":\"user\"}", MediaType.APPLICATION_JSON));
	services.loadAuthentication("FOO");
	assertThat(client.getAccessToken().getValue()).isEqualTo("FOO");
	server.verify();
}
 
Example #4
Source File: XmlContentRequestMatchersIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {

	List<Person> composers = Arrays.asList(
			new Person("Johann Sebastian Bach").setSomeDouble(21),
			new Person("Johannes Brahms").setSomeDouble(.0025),
			new Person("Edvard Grieg").setSomeDouble(1.6035),
			new Person("Robert Schumann").setSomeDouble(Double.NaN));

	this.people = new PeopleWrapper(composers);

	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new Jaxb2RootElementHttpMessageConverter());

	this.restTemplate = new RestTemplate();
	this.restTemplate.setMessageConverters(converters);

	this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
 
Example #5
Source File: UserManagementServiceTest.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
private void mockGetUsersFromRoleServer(MockRestServiceServer server) {
    server.expect(ExpectedCount.manyTimes(), requestTo(String.format("http://%s/auth/v1/roles/%s/users", this.gatewayUrl, ROLE_ID)))
            .andExpect(method(HttpMethod.GET))
            .andExpect(header("Authorization", TOKEN))
            .andRespond(withSuccess(String.format("{\n" +
                    "  \"status\": \"OK\",\n" +
                    "  \"message\": \"success\",\n" +
                    "  \"data\": [\n" +
                    "    {\n" +
                    "      \"createdBy\": null,\n" +
                    "      \"updatedBy\": null,\n" +
                    "      \"createdTime\": \"2019-12-04T06:56:18.000+0000\",\n" +
                    "      \"updatedTime\": null,\n" +
                    "      \"id\": 1,\n" +
                    "      \"username\": \"%s\",\n" +
                    "      \"password\": \"%s\",\n" +
                    "      \"active\": true,\n" +
                    "      \"blocked\": null\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}", USERNAME, AS_RETURN_PASSWORD), MediaType.APPLICATION_JSON));

}
 
Example #6
Source File: UserManagementServiceTest.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
private void mockGetRolesFromUserServer(MockRestServiceServer server) {
    server.expect(ExpectedCount.manyTimes(), requestTo(String.format("http://%s/auth/v1/users/%s/roles", this.gatewayUrl, USERNAME)))
            .andExpect(method(HttpMethod.GET))
            .andExpect(header("Authorization", TOKEN))
            .andRespond(withSuccess(String.format("{\n" +
                    "  \"status\": \"OK\",\n" +
                    "  \"message\": \"success\",\n" +
                    "  \"data\": [\n" +
                    "    {\n" +
                    "      \"createdBy\": null,\n" +
                    "      \"updatedBy\": null,\n" +
                    "      \"createdTime\": \"2019-12-04T06:56:39.000+0000\",\n" +
                    "      \"updatedTime\": null,\n" +
                    "      \"id\": \"1\",\n" +
                    "      \"name\": \"%s\",\n" +
                    "      \"displayName\": \"%s\",\n" +
                    "      \"email\": \"%s\"\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}", ROLE_NAME, ROLE_DISPLAY_NAME, ROLE_EMAIL), MediaType.APPLICATION_JSON));

}
 
Example #7
Source File: ExecuteTest.java    From riptide with MIT License 6 votes vote down vote up
@Test
void shouldFailIfNoConverterFoundForBodyOfUnknownContentType() {
    final MockSetup setup = new MockSetup("https://api.example.com", Collections.emptyList());
    final MockRestServiceServer server = setup.getServer();
    final Http unit = setup.getHttpBuilder()
            .converter(new Jaxb2RootElementHttpMessageConverter()).build();

    // we never actually make the request, but the mock server is doing some magic pre-actively
    server.expect(requestTo(url))
            .andRespond(withSuccess());

    final CompletionException exception = assertThrows(CompletionException.class, () ->
            unit.delete(url)
                    .body(new Success(true))
                    .dispatch(contentType())
                    .join());

    assertThat(exception.getCause(), is(instanceOf(RestClientException.class)));
    assertThat(exception.getMessage(), containsString("no suitable HttpMessageConverter found"));
    assertThat(exception.getMessage(), containsString("org.zalando.riptide.model.Success"));
}
 
Example #8
Source File: UserManagementServiceTest.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
private void mockRetrieveRoleServer(MockRestServiceServer server) {
    server.expect(ExpectedCount.manyTimes(), requestTo(String.format("http://%s/auth/v1/roles", this.gatewayUrl)))
            .andExpect(method(HttpMethod.GET))
            .andExpect(header("Authorization", TOKEN))
            .andRespond(withSuccess(String.format("{\n" +
                    "  \"status\": \"OK\",\n" +
                    "  \"message\": \"success\",\n" +
                    "  \"data\": [\n" +
                    "    {\n" +
                    "      \"createdBy\": null,\n" +
                    "      \"updatedBy\": null,\n" +
                    "      \"createdTime\": \"2019-12-04T06:37:40.000+0000\",\n" +
                    "      \"updatedTime\": null,\n" +
                    "      \"id\": \"1\",\n" +
                    "      \"name\": \"%s\",\n" +
                    "      \"displayName\": \"%s\",\n" +
                    "      \"email\": \"%s\"\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}", ROLE_NAME, ROLE_DISPLAY_NAME, ROLE_EMAIL), MediaType.APPLICATION_JSON));

}
 
Example #9
Source File: UserManagementServiceTest.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
private void mockRetrieveRoleByIdServer(MockRestServiceServer server) {
    server.expect(ExpectedCount.manyTimes(), requestTo(String.format("http://%s/auth/v1/roles/%s", this.gatewayUrl, ROLE_ID)))
            .andExpect(method(HttpMethod.GET))
            .andExpect(header("Authorization", TOKEN))
            .andRespond(withSuccess(String.format("{\n" +
                    "  \"status\": \"OK\",\n" +
                    "  \"message\": \"success\",\n" +
                    "  \"data\":\n" +
                    "    {\n" +
                    "      \"createdBy\": null,\n" +
                    "      \"updatedBy\": null,\n" +
                    "      \"createdTime\": \"2019-12-04T06:37:40.000+0000\",\n" +
                    "      \"updatedTime\": null,\n" +
                    "      \"id\": \"1\",\n" +
                    "      \"name\": \"%s\",\n" +
                    "      \"displayName\": \"%s\",\n" +
                    "      \"email\": \"%s\"\n" +
                    "    }\n" +
                    "}", ROLE_NAME, ROLE_DISPLAY_NAME, ROLE_EMAIL), MediaType.APPLICATION_JSON));

}
 
Example #10
Source File: UserManagementServiceTest.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
private void mockRegisterRoleServer(MockRestServiceServer server) {
    String createRoleJsonString = String.format("{\"displayName\":\"%s\",\"name\":\"%s\",\"email\":\"%s\"}", ROLE_DISPLAY_NAME, ROLE_NAME, ROLE_EMAIL);
    server.expect(ExpectedCount.manyTimes(), requestTo(String.format("http://%s/auth/v1/roles", this.gatewayUrl)))
            .andExpect(method(HttpMethod.POST))
            .andExpect(header("Authorization", TOKEN))
            .andExpect(content().json(createRoleJsonString))
            .andRespond(withSuccess(String.format("{\n" +
                    "  \"status\": \"OK\",\n" +
                    "  \"message\": \"success\",\n" +
                    "  \"data\": {\n" +
                    "    \"createdBy\": null,\n" +
                    "    \"updatedBy\": null,\n" +
                    "    \"createdTime\": \"2019-12-04T06:37:39.805+0000\",\n" +
                    "    \"updatedTime\": null,\n" +
                    "    \"id\": \"1\",\n" +
                    "    \"name\": \"%s\",\n" +
                    "    \"displayName\": \"%s\",\n" +
                    "    \"email\": \"%s\"\n" +
                    "  }\n" +
                    "}", ROLE_NAME, ROLE_DISPLAY_NAME, ROLE_EMAIL), MediaType.APPLICATION_JSON));
}
 
Example #11
Source File: UserManagementServiceTest.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
private void mockCreateUserServer(MockRestServiceServer server) {
    String createUserJsonString = String.format("{\"password\":\"%s\",\"username\":\"%s\"}", MOCK_PASSWORD, MOCK_USERNAME);
    server.expect(ExpectedCount.manyTimes(), requestTo(String.format("http://%s/auth/v1/users", this.gatewayUrl)))
            .andExpect(method(HttpMethod.POST))
            .andExpect(header("Authorization", TOKEN))
            .andExpect(content().json(createUserJsonString))
            .andRespond(withSuccess(String.format("{\n" +
                    "  \"status\": \"OK\",\n" +
                    "  \"message\": \"success\",\n" +
                    "  \"data\": {\n" +
                    "    \"createdBy\": null,\n" +
                    "    \"updatedBy\": null,\n" +
                    "    \"createdTime\": \"2019-12-04T06:34:06.110+0000\",\n" +
                    "    \"updatedTime\": null,\n" +
                    "    \"id\": 1,\n" +
                    "    \"username\": \"%s\",\n" +
                    "    \"password\": \"%s\",\n" +
                    "    \"active\": true,\n" +
                    "    \"blocked\": null\n" +
                    "  }\n" +
                    "}", MOCK_USERNAME, AS_RETURN_PASSWORD), MediaType.APPLICATION_JSON));

}
 
Example #12
Source File: StatusDispatchTest.java    From riptide with MIT License 6 votes vote down vote up
@ParameterizedTest
@MethodSource("data")
void shouldDispatch(final HttpStatus expected) {
    final MockSetup setup = new MockSetup();
    final MockRestServiceServer server = setup.getServer();
    final Http unit = setup.getHttp();

    final URI url = URI.create("https://api.example.com");

    server.expect(requestTo(url)).andRespond(withStatus(expected));

    final ClientHttpResponseConsumer verifier = response ->
            assertThat(response.getStatusCode(), is(expected));

    @SuppressWarnings("unchecked")
    final Binding<HttpStatus>[] bindings = HttpStatuses.supported()
            .map(status -> on(status).call(verifier))
            .toArray(Binding[]::new);

    unit.get(url).dispatch(status(), bindings);
}
 
Example #13
Source File: DefaultSkipperClientTests.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@Test
public void testScaleByReleaseAndScaleRequest() {
	RestTemplate restTemplate = new RestTemplate();
	SkipperClient skipperClient = new DefaultSkipperClient("", restTemplate);

	MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
	mockServer
		.expect(requestTo("/release/scale/mylog"))
		.andExpect(content().json("{\"scale\":[{\"name\":\"app\",\"count\":2,\"properties\":{}}]}"))
		.andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));

	ScaleRequest scaleRequest = ScaleRequest.of("app", 2);
	Release release = skipperClient.scale("mylog", scaleRequest);
	mockServer.verify();

	assertThat(release).isNotNull();
}
 
Example #14
Source File: UriTemplateArgTest.java    From riptide with MIT License 6 votes vote down vote up
@ParameterizedTest
@MethodSource("data")
void shouldExpand(final String baseUrl, final String uriTemplate, final Object[] uriVariables,
        final String requestUrl) {

    final MockSetup setup = new MockSetup(baseUrl);
    final MockRestServiceServer server = setup.getServer();
    final Http unit = setup.getHttp();

    server.expect(requestTo(requestUrl))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess());

    unit.get(uriTemplate, uriVariables)
            .dispatch(series(),
                    on(SUCCESSFUL).call(pass()))
            .join();

    server.verify();
}
 
Example #15
Source File: SampleTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test // SPR-14694
public void repeatedAccessToResponseViaResource() {

	Resource resource = new ClassPathResource("ludwig.json", this.getClass());

	RestTemplate restTemplate = new RestTemplate();
	restTemplate.setInterceptors(Collections.singletonList(new ContentInterceptor(resource)));

	MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate)
			.ignoreExpectOrder(true)
			.bufferContent()  // enable repeated reads of response body
			.build();

	mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
			.andRespond(withSuccess(resource, MediaType.APPLICATION_JSON));

	restTemplate.getForObject("/composers/{id}", Person.class, 42);

	mockServer.verify();
}
 
Example #16
Source File: SampleTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test // SPR-14694
public void repeatedAccessToResponseViaResource() {

	Resource resource = new ClassPathResource("ludwig.json", this.getClass());

	RestTemplate restTemplate = new RestTemplate();
	restTemplate.setInterceptors(Collections.singletonList(new ContentInterceptor(resource)));

	MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate)
			.ignoreExpectOrder(true)
			.bufferContent()  // enable repeated reads of response body
			.build();

	mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
			.andRespond(withSuccess(resource, MediaType.APPLICATION_JSON));

	restTemplate.getForObject("/composers/{id}", Person.class, 42);

	mockServer.verify();
}
 
Example #17
Source File: HttpFileTransferImplTest.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Setup for the tests.
 */
@Before
public void setup() {
    final RestTemplate restTemplate = new RestTemplate();
    this.server = MockRestServiceServer.createServer(restTemplate);
    this.downloadTimer = Mockito.mock(Timer.class);
    this.uploadTimer = Mockito.mock(Timer.class);
    this.metadataTimer = Mockito.mock(Timer.class);
    this.registry = Mockito.mock(MeterRegistry.class);
    Mockito
        .when(registry.timer(Mockito.eq(HttpFileTransferImpl.DOWNLOAD_TIMER_NAME), Mockito.anySet()))
        .thenReturn(this.downloadTimer);
    Mockito
        .when(registry.timer(Mockito.eq(HttpFileTransferImpl.UPLOAD_TIMER_NAME), Mockito.anySet()))
        .thenReturn(this.uploadTimer);
    Mockito
        .when(registry.timer(Mockito.eq(HttpFileTransferImpl.GET_LAST_MODIFIED_TIMER_NAME), Mockito.anySet()))
        .thenReturn(this.metadataTimer);
    this.httpFileTransfer = new HttpFileTransferImpl(restTemplate, this.registry);
}
 
Example #18
Source File: XmlContentRequestMatchersIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
public void setup() {
	List<Person> composers = Arrays.asList(
			new Person("Johann Sebastian Bach").setSomeDouble(21),
			new Person("Johannes Brahms").setSomeDouble(.0025),
			new Person("Edvard Grieg").setSomeDouble(1.6035),
			new Person("Robert Schumann").setSomeDouble(Double.NaN));

	this.people = new PeopleWrapper(composers);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new Jaxb2RootElementHttpMessageConverter());

	this.restTemplate = new RestTemplate();
	this.restTemplate.setMessageConverters(converters);

	this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
 
Example #19
Source File: XpathRequestMatchersIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setup() {
	List<Person> composers = Arrays.asList(
			new Person("Johann Sebastian Bach").setSomeDouble(21),
			new Person("Johannes Brahms").setSomeDouble(.0025),
			new Person("Edvard Grieg").setSomeDouble(1.6035),
			new Person("Robert Schumann").setSomeDouble(Double.NaN));

	List<Person> performers = Arrays.asList(
			new Person("Vladimir Ashkenazy").setSomeBoolean(false),
			new Person("Yehudi Menuhin").setSomeBoolean(true));

	this.people = new PeopleWrapper(composers, performers);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new Jaxb2RootElementHttpMessageConverter());

	this.restTemplate = new RestTemplate();
	this.restTemplate.setMessageConverters(converters);

	this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
 
Example #20
Source File: AwsIamAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void before() {

	RestTemplate restTemplate = VaultClients.createRestTemplate();
	restTemplate.setUriTemplateHandler(new PrefixAwareUriTemplateHandler());

	this.mockRest = MockRestServiceServer.createServer(restTemplate);
	this.restTemplate = restTemplate;
}
 
Example #21
Source File: OAuth2RestTemplateIntegrationTest.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@Test
public void testOAuth2RestTemplate() throws Exception {
    final AccessTokens mockAccessTokens = mock(AccessTokens.class);
    when(mockAccessTokens.get(anyObject()))
            .thenReturn("token-0815")
            .thenReturn("token-4711");
    when(mockAccessTokens.getAccessToken(anyObject()))
            // first token is already expired
            .thenReturn(new AccessToken("token-0815", "bearer", 3600, now().minusHours(1).toDate()))
                    // second token is valid
            .thenReturn(new AccessToken("token-4711", "bearer", 3600, now().plusHours(1).toDate()));

    final StupsOAuth2RestTemplate restTemplate = new StupsOAuth2RestTemplate(
            new StupsTokensAccessTokenProvider("unit-test", mockAccessTokens));
    restTemplate.setErrorHandler(new PassThroughErrorHandler());

    final MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);

    // first request with invalid token
    mockServer.expect(requestTo("/first"))
              .andExpect(method(GET))
              .andExpect(header("Authorization", "Bearer token-0815"))
              .andRespond(withUnauthorizedRequest());

    // second request with valid token
    mockServer.expect(requestTo("/second"))
              .andExpect(method(GET))
              .andExpect(header("Authorization", "Bearer token-4711"))
              .andRespond(withUnauthorizedRequest());

    // perform first request
    restTemplate.getForEntity("/first", String.class);
    // perform second request
    restTemplate.getForEntity("/second", String.class);

    mockServer.verify();
}
 
Example #22
Source File: WireMockRestServiceServer.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private ResponseActions responseActions(MockRestServiceServer server,
		StubMapping mapping) {
	if (StringUtils.hasText(mapping.getRequest().getUrl())
			|| StringUtils.hasText(mapping.getRequest().getUrlPath())) {
		return server.expect(requestTo(request(mapping.getRequest())));
	}
	return server.expect(requestTo(requestMatcher(mapping.getRequest())));
}
 
Example #23
Source File: DefaultSkipperClientTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogByReleaseName() {
	RestTemplate restTemplate = new RestTemplate();
	SkipperClient skipperClient = new DefaultSkipperClient("", restTemplate);

	MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
	mockServer.expect(requestTo("/release/logs/mylog")).andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));

	LogInfo logContent = skipperClient.getLog("mylog");
	mockServer.verify();

	assertThat(logContent).isNotNull();
}
 
Example #24
Source File: HeaderRequestMatchersIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new StringHttpMessageConverter());
	converters.add(new MappingJackson2HttpMessageConverter());

	this.restTemplate = new RestTemplate();
	this.restTemplate.setMessageConverters(converters);

	this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
 
Example #25
Source File: DefaultSkipperClientTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test(expected = PackageDeleteException.class)
public void testDeletePackageHasDeployedRelease() {
	RestTemplate restTemplate = new RestTemplate();
	restTemplate.setErrorHandler(new SkipperClientResponseErrorHandler(new ObjectMapper()));
	SkipperClient skipperClient = new DefaultSkipperClient("", restTemplate);

	MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
	mockServer.expect(requestTo("/release/release1/package"))
			.andRespond(withStatus(HttpStatus.CONFLICT).body(ERROR3).contentType(MediaType.APPLICATION_JSON));
	skipperClient.delete("release1", true);
}
 
Example #26
Source File: DefaultSkipperClientTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test(expected = SkipperException.class)
public void testSkipperException() {
	RestTemplate restTemplate = new RestTemplate();
	restTemplate.setErrorHandler(new SkipperClientResponseErrorHandler(new ObjectMapper()));
	SkipperClient skipperClient = new DefaultSkipperClient("", restTemplate);

	MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
	mockServer.expect(requestTo("/release/status/mylog"))
			.andRespond(withStatus(HttpStatus.NOT_FOUND).body(ERROR2).contentType(MediaType.APPLICATION_JSON));

	skipperClient.status("mylog");
}
 
Example #27
Source File: WiremockMockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleGet() throws Exception {
	MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
			.baseUrl("https://example.org") //
			.stubs("classpath:/mappings/resource.json").build();
	assertThat(this.restTemplate.getForObject("https://example.org/resource",
			String.class)).isEqualTo("Hello World");
	server.verify();
}
 
Example #28
Source File: VaultClientsUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldApplyNamespace() {

	RestTemplate restTemplate = VaultClients.createRestTemplate();
	restTemplate.getInterceptors().add(VaultClients.createNamespaceInterceptor("foo/bar"));
	restTemplate.setUriTemplateHandler(new PrefixAwareUriTemplateHandler());

	MockRestServiceServer mockRest = MockRestServiceServer.createServer(restTemplate);

	mockRest.expect(requestTo("/auth/foo")).andExpect(method(HttpMethod.GET))
			.andExpect(header(VaultHttpHeaders.VAULT_NAMESPACE, "foo/bar")).andRespond(withSuccess());

	restTemplate.getForEntity("/auth/foo", String.class);
}
 
Example #29
Source File: ClusterProxyRegistrationClientTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    RestTemplate restTemplate = new RestTemplate();
    mockServer = MockRestServiceServer.createServer(restTemplate);
    service = new ClusterProxyRegistrationClient(restTemplate);

    ClusterProxyConfiguration proxyConfig = spy(ClusterProxyConfiguration.class);
    ReflectionTestUtils.setField(proxyConfig, "clusterProxyUrl", CLUSTER_PROXY_URL);
    ReflectionTestUtils.setField(proxyConfig, "registerConfigPath", REGISTER_CONFIG_PATH);
    ReflectionTestUtils.setField(proxyConfig, "updateConfigPath", UPDATE_CONFIG_PATH);
    ReflectionTestUtils.setField(proxyConfig, "removeConfigPath", REMOVE_CONFIG_PATH);

    ReflectionTestUtils.setField(service, "clusterProxyConfiguration", proxyConfig);
}
 
Example #30
Source File: WiremockMockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleGetWithBodyFileCustomLocation() throws Exception {
	MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) //
			.baseUrl("https://example.org") //
			.stubs("classpath:/mappings/resource-with-body-file.json")
			.files("classpath:/custom/").build();
	assertThat(this.restTemplate.getForObject("https://example.org/resource",
			String.class))
					.isEqualToIgnoringWhitespace("{\"message\":\"Hello Custom\"}");
	server.verify();
}