Why doesn't the java.net.URI
constructor throw an exception when I pass in a string like "abc"? I've isolated it to the test case below.
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class HelloWorldTest {
@Test(expected=URISyntaxException.class)
public void testAlphabeticStringWithUriConstructor()
throws URISyntaxException {
URI uri = new URI("abc");
}
}
Which, when compiled and run, produces the following:
$ java -cp .:lib/junit-4.12.jar:lib/hamcrest-core-1.3.jar org.junit.runner.JUnitCore HelloWorldTest
JUnit version 4.12
.E
Time: 0.005
There was 1 failure:
1) testAlphabeticStringWithUriConstructor(HelloWorldTest)
java.lang.AssertionError: Expected exception: java.net.URISyntaxException
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.runner.JUnitCore.runMain(JUnitCore.java:77)
at org.junit.runner.JUnitCore.main(JUnitCore.java:36)
FAILURES!!!
Tests run: 1, Failures: 1
According to the javadocs for URI, the constructor java.net.URI
should throw a URISyntaxException
"if the given string violates RFC 2396, as augmented by the above deviations" with some minor deviations included. And the URI constructor does catch other malformed URIs. But for some reason it seems to be okay with this one. Is it possible that "abc" is a valid URI? RFC 2396 - Uniform Resource Identifier (URI): Generic Syntax does not clearly indicate it if so.
Ultimately, this is a problem because I would like to validate that a user-supplied string is a URI before attempting to make an HTTP request.