Recent articles:
Popular archives:
Java: A platform for platforms
Sun's reorg may seem promising to shareholders but it's also a scramble for position. The question now is whether Sun can,
or wants to, maintain its hold on Java technology. Especially with enterprise leaders like SpringSource and RedHat investing
heavily in Java's future as a platform for platforms
Also see:
Discuss: Tim Bray on 'What Sun Should Do'
For the last two months, I've described testing, I've explained its terminology, and I've explained how it works. This month, I move from the abstract to the concrete by presenting a simple framework for unit and component testing. If you're joining us for the first time, you might want to read the first two articles in the series before launching into our sample code.
For the purposes of this article, we will build and test a simple scanner. Our scanner will search a string for javadoc tags
(that is, lines that begin with the @ character).
Let's take a look at our scanner's code:
import java.util.Vector;
public
class Scanner {
public
int
scan(Vector vector, String string, int nBegin, int nLength) {
if (vector == null)
throw new NullPointerException("vector");
if (string == null)
throw new NullPointerException("string");
if (nBegin + nLength > string.length())
throw new StringIndexOutOfBoundsException("nBegin + nLength > string.length()");
if (nBegin < 0)
throw new StringIndexOutOfBoundsException("nBegin < 0");
if (nLength < 0) nLength = string.length() - nBegin;
vector.removeAllElements();
int n1 = string.indexOf("/**", nBegin);
if (n1 < nBegin)
return -1;
int n2 = string.indexOf("*/", n1 + 3);
if (n2 < 0 || n2 > nBegin + nLength)
return -1;
StringBuffer stringbuffer = null;
int n = n1 + 3;
while (n < n2) {
int nEOL = string.indexOf("\r\n", n);
int nNextLine = nEOL + 2;
if (nEOL < 0) {
nEOL = string.indexOf('\r', n);
nNextLine = nEOL + 1;
}
if (nEOL < 0) {
nEOL = string.indexOf('\n', n);
nNextLine = nEOL + 1;
}
if (nEOL < 0) {
nEOL = n2;
nNextLine = nEOL;
}
if (nEOL > n2) {
nEOL = n2;
nNextLine = nEOL;
}
if (nEOL > n) {
char c = string.charAt(n);
while ((c == ' ' || c == '\t' || c == '*') && n < n2)
c = string.charAt(++n);
if (string.charAt(n) == '@') {
if (stringbuffer != null) vector.addElement(stringbuffer);
stringbuffer = new StringBuffer();
}
if (stringbuffer != null) stringbuffer.append(string.substring(n, nEOL));
}
n = nNextLine;
}
if (stringbuffer != null) vector.addElement(stringbuffer);
return n2 + 2;
}
}
The scan() method searches the supplied string for a javadoc-style comment (that is, a comment that begins with /** and ends with */). If it finds one, it searches the body of the comment for lines that begin with the @ character. These lines begin javadoc tags. Upon finding such a tag, scan() copies it, along with all subsequent lines up to the next tag or up to the end of the comment, into a collection. Once it
has found all such tags, it returns both the collection and the point at which it stopped searching.