ResourceDecoderTests.java 2.6 KB
Newer Older
1
/*
2
 * Copyright 2002-2018 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
package org.springframework.core.codec;
18 19

import java.io.IOException;
20
import java.util.Collections;
21 22 23

import org.junit.Test;
import reactor.core.publisher.Flux;
24
import reactor.test.StepVerifier;
25 26 27 28

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
29
import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase;
30
import org.springframework.core.io.buffer.DataBuffer;
31
import org.springframework.util.MimeTypeUtils;
32 33
import org.springframework.util.StreamUtils;

34 35
import static org.junit.Assert.*;
import static org.springframework.core.ResolvableType.*;
36 37 38 39

/**
 * @author Arjen Poutsma
 */
40
public class ResourceDecoderTests extends AbstractDataBufferAllocatingTestCase {
41 42 43 44

	private final ResourceDecoder decoder = new ResourceDecoder();

	@Test
45 46 47 48 49 50
	public void canDecode() {
		assertTrue(this.decoder.canDecode(forClass(InputStreamResource.class), MimeTypeUtils.TEXT_PLAIN));
		assertTrue(this.decoder.canDecode(forClass(ByteArrayResource.class), MimeTypeUtils.TEXT_PLAIN));
		assertTrue(this.decoder.canDecode(forClass(Resource.class), MimeTypeUtils.TEXT_PLAIN));
		assertTrue(this.decoder.canDecode(forClass(InputStreamResource.class), MimeTypeUtils.APPLICATION_JSON));
		assertFalse(this.decoder.canDecode(forClass(Object.class), MimeTypeUtils.APPLICATION_JSON));
51 52 53
	}

	@Test
54
	public void decode() {
55 56 57 58
		DataBuffer fooBuffer = stringBuffer("foo");
		DataBuffer barBuffer = stringBuffer("bar");
		Flux<DataBuffer> source = Flux.just(fooBuffer, barBuffer);

59
		Flux<Resource> result = this.decoder
60
				.decode(source, forClass(Resource.class), null, Collections.emptyMap());
61

62
		StepVerifier.create(result)
63
				.consumeNextWith(resource -> {
64
					try {
65
						byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
66 67 68 69 70
						assertEquals("foobar", new String(bytes));
					}
					catch (IOException e) {
						fail(e.getMessage());
					}
71 72
				})
				.expectComplete()
73
				.verify();
74 75
	}

76
}