BAEL-5745 Mocking InputStream (#12845)

This commit is contained in:
mdabrowski-eu 2022-10-11 10:14:08 +02:00 committed by GitHub
parent e346b931f7
commit c4052100a0
3 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package com.baeldung.mockinginputstream;
import java.io.IOException;
import java.io.InputStream;
public class GeneratingInputStream extends InputStream {
private final int desiredSize;
private int actualSize = 0;
private final byte[] seed;
public GeneratingInputStream(int desiredSize, String seed) {
this.desiredSize = desiredSize;
this.seed = seed.getBytes();
}
@Override
public int read() {
if (actualSize >= desiredSize) {
return -1;
}
return seed[actualSize++ % seed.length];
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.mockinginputstream;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
public class MockingInputStreamUnitTest {
@Test
public void givenSimpleImplementation_shouldProcessInputStream() throws IOException {
int byteCount = processInputStream(new InputStream() {
private final byte[] msg = "Hello World".getBytes();
private int index = 0;
@Override
public int read() {
if (index >= msg.length) {
return -1;
}
return msg[index++];
}
});
assertThat(byteCount).isEqualTo(11);
}
@Test
public void givenByteArrayInputStream_shouldProcessInputStream() throws IOException {
String msg = "Hello World";
int bytesCount = processInputStream(new ByteArrayInputStream(msg.getBytes()));
assertThat(bytesCount).isEqualTo(11);
}
@Test
public void givenFileInputStream_shouldProcessInputStream() throws IOException {
InputStream inputStream = MockingInputStreamUnitTest.class.getResourceAsStream("/mockinginputstreams/msg.txt");
int bytesCount = processInputStream(inputStream);
assertThat(bytesCount).isEqualTo(11);
inputStream.close();
}
@Test
public void givenGeneratingInputStream_shouldProcessInputStream() throws IOException {
InputStream inputStream = new GeneratingInputStream(10_000, "Hello World");
int bytesCount = processInputStream(inputStream);
assertThat(bytesCount).isEqualTo(10_000);
inputStream.close();
}
int processInputStream(InputStream inputStream) throws IOException {
int count = 0;
while(inputStream.read() != -1) {
count++;
}
return count;
}
}