StringReaderInputStream
Have you every made your own InputStream such as a text formatter or a url extractor. In my case, I made an InputStream that can extract urls from any other InputStream and send those urls to an interface called LinkEater. What I want to talk about in this post is how I tested my LinkParserInputStream.
Everyone that claims to know java should know how InputStreams are designed. They use composition to modify the behavior or other InputStreams. InputStreams are a classic example of the Decorator pattern. I took advantage of this pattern when I made my LinkParserInputStream. It obviously HAS-A InputStream and when it is read from it looks for urls in its composit partner. Just what kind of InputStream can it contain? Well any, but what if you want to test it.
To test my LinkParserInputStream I made a class that can read from a string and return characters like an InputStream. By combining a StringReader with the InputStream interface I was able to do this very simply. I believe this pattern is called the Adapter pattern. Here is how the class turned out...
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
public class StringReaderInputStream extends InputStream {
protected StringReader stringReader;
protected String string;
public StringReaderInputStream(String string) {
stringReader = new StringReader(string);
this.string = string;
}
@Override
public int read() throws IOException {
return stringReader.read();
}
@Override
public String toString() {
return string;
}
}
Now I am able to create an InputStream from any String I want and test my LinkParserInputStream. With this I was able to extensivly test my class with 60 different cases that I made. Each case representing a different way a url could be found in html. I have also used this in my WordParserInputStream...