001/*
002 * Copyright 2002-2020 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.mock.http;
018
019import java.io.ByteArrayOutputStream;
020import java.io.IOException;
021import java.io.OutputStream;
022import java.nio.charset.Charset;
023import java.nio.charset.StandardCharsets;
024
025import org.springframework.http.HttpHeaders;
026import org.springframework.http.HttpOutputMessage;
027import org.springframework.util.StreamUtils;
028
029/**
030 * Mock implementation of {@link HttpOutputMessage}.
031 *
032 * @author Rossen Stoyanchev
033 * @since 3.2
034 */
035public class MockHttpOutputMessage implements HttpOutputMessage {
036
037        private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
038
039        private final HttpHeaders headers = new HttpHeaders();
040
041        private final ByteArrayOutputStream body = new ByteArrayOutputStream(1024);
042
043
044        /**
045         * Return the headers.
046         */
047        @Override
048        public HttpHeaders getHeaders() {
049                return this.headers;
050        }
051
052        /**
053         * Return the body content.
054         */
055        @Override
056        public OutputStream getBody() throws IOException {
057                return this.body;
058        }
059
060        /**
061         * Return body content as a byte array.
062         */
063        public byte[] getBodyAsBytes() {
064                return this.body.toByteArray();
065        }
066
067        /**
068         * Return the body content interpreted as a UTF-8 string.
069         */
070        public String getBodyAsString() {
071                return getBodyAsString(DEFAULT_CHARSET);
072        }
073
074        /**
075         * Return the body content as a string.
076         * @param charset the charset to use to turn the body content to a String
077         */
078        public String getBodyAsString(Charset charset) {
079                return StreamUtils.copyToString(this.body, charset);
080        }
081
082}