001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.test.web.client; 018 019import java.io.IOException; 020import java.util.Iterator; 021 022import org.springframework.http.client.ClientHttpRequest; 023import org.springframework.http.client.ClientHttpResponse; 024import org.springframework.util.Assert; 025 026/** 027 * Simple {@code RequestExpectationManager} that matches requests to expectations 028 * sequentially, i.e. in the order of declaration of expectations. 029 * 030 * <p>When request expectations have an expected count greater than one, 031 * only the first execution is expected to match the order of declaration. 032 * Subsequent request executions may be inserted anywhere thereafter. 033 * 034 * @author Rossen Stoyanchev 035 * @author Juergen Hoeller 036 * @since 4.3 037 */ 038public class SimpleRequestExpectationManager extends AbstractRequestExpectationManager { 039 040 /** Expectations in the order of declaration (count may be > 1) */ 041 private Iterator<RequestExpectation> expectationIterator; 042 043 /** Track expectations that have a remaining count */ 044 private final RequestExpectationGroup repeatExpectations = new RequestExpectationGroup(); 045 046 047 @Override 048 protected void afterExpectationsDeclared() { 049 Assert.state(this.expectationIterator == null, "Expectations already declared"); 050 this.expectationIterator = getExpectations().iterator(); 051 } 052 053 @Override 054 public ClientHttpResponse validateRequestInternal(ClientHttpRequest request) throws IOException { 055 RequestExpectation expectation = this.repeatExpectations.findExpectation(request); 056 if (expectation == null) { 057 if (!this.expectationIterator.hasNext()) { 058 throw createUnexpectedRequestError(request); 059 } 060 expectation = this.expectationIterator.next(); 061 expectation.match(request); 062 } 063 ClientHttpResponse response = expectation.createResponse(request); 064 this.repeatExpectations.update(expectation); 065 return response; 066 } 067 068 @Override 069 public void reset() { 070 super.reset(); 071 this.expectationIterator = null; 072 this.repeatExpectations.reset(); 073 } 074 075}