Testing invalid Java URI and URL inputs
Java services often treat URLs as harmless strings until a request reaches a route, client, redirect builder, or allowlist. That delay makes malformed values dangerous: a broken percent escape, illegal host, or misleading authority can trigger inconsistent behaviour far from the parser. Invalid-input testing exposes these failures before they become runtime errors or security weaknesses.
This guide focuses on java.net.URI and java.net.URL, using JUnit-style examples to separate syntax errors from values that parse but should fail business rules. The goal is not to predict every exception message. It is to establish a clear test oracle for rejection, normalisation, and safe downstream handling, including fixtures familiar to Australian teams.
Why malformed inputs need dedicated tests
URI and URL parsers enforce different contracts. java.net.URI treats a value as a structured identifier with optional scheme, authority, path, query, and fragment. java.net.URL combines a locator with protocol-specific handling and has historically been more permissive. A negative test should therefore target one parser at a time instead of assuming both reject the same malformed string.
That distinction matters because parsing, validation, and use are separate stages. A parser may accept a relative reference that an HTTP client cannot use; a URL may retain an invalid escape that a route later decodes; an allowlist may reject a syntactically valid but untrusted host. The useful oracle is precise: which stage rejects the value, which exception or status appears, and whether any sensitive normalisation occurs before rejection.
Build a corpus of hostile URI values
Start with a compact corpus of malformed strings. Include a missing scheme, raw spaces, tabs, line breaks, a lone percent sign, non-hexadecimal escapes such as %GG, truncated percent sequences, unmatched square brackets, malformed IPv6 literals, and authority strings containing several @ characters. Vary position as well as content: put each defect in the host, port, path, query, and fragment so the parser’s state transitions are exercised.
Add valid-but-dangerous boundary values. Examples include //host/path without a scheme, https://user@host/path, uppercase schemes, an empty authority, paths beginning with //, encoded slashes, encoded nulls, and queries containing # or &. Property-based testing can generate character sequences and assert invariants such as “a rejected input causes no outbound request” or “a parsed authority always has one unambiguous host interpretation.” Keep generated values deterministic in CI by recording the failing seed and replaying it as a normal regression test.
Separate URI and URL parser contracts
java.net.URI provides the clearest syntax boundary. Its string constructor declares URISyntaxException, while URI.create exposes the same failure as IllegalArgumentException. Test the API used by production code, and assert the exception type rather than a vendor-specific message. Remember that a relative URI is valid even though it is not a complete URL.
A truncated escape illustrates the basic negative case:
@Test
void uriRejectsMalformedEscape() {
assertThrows(URISyntaxException.class,
() -> new URI("https://example.com.au/orders/%2"));
}
Here, rejection occurs during parsing, before any routing decision. A similar test can use URI.create and expect IllegalArgumentException; the wrapper changes the public failure type, not the underlying reason for rejection.
java.net.URL is less suitable as a strict validator. The legacy URL(String) constructor is deprecated in recent Java releases, and URI.toURL() is usually preferable, yet both rely on protocol and authority rules that differ from URI syntax checks. A URL may accept path content that a URI rejects or preserve an invalid percent sequence. Tests should document which strings are genuinely malformed and which are merely unsuitable for HTTP use.
Turn parser behaviour into stable assertions
Stable assertions make the negative suite easy to maintain. A parameterized JUnit test can cover several broken authorities without duplicating logic:
@ParameterizedTest
@ValueSource(strings = {
"https://example.com.au/%",
"https://example.com.au/%GG",
"https://[2001:db8::1/orders"
})
void malformedUriIsRejected(String input) {
assertThrows(URISyntaxException.class, () -> new URI(input));
}
Do not assert the full exception text; it tends to change between JDK releases. Assert the exception category, and add a domain-specific error code only when the application guarantees one. This keeps unit tests coupled to behaviour rather than incidental wording. The same corpus can also feed a Spock data-driven feature in a Groovy build without changing the underlying test oracle.
The oracle changes for accepted inputs. For a relative URI, assert isAbsolute() is false and that conversion to a URL fails as expected. For accepted authorities, inspect both raw and decoded components, especially when %2F, %40, or mixed-case escapes could change host, path, or user-info interpretation. Where supported, fuzzing and property-based tests should check round trips and ensure rejection happens before DNS resolution, socket creation, or redirect emission.
Test security boundaries in delivery pipelines
Parser tests are only one layer. Exercise the REST route, HTTP client, webhook verifier, and redirect builder with hostile authority values. The classic security case is server-side request forgery: an input such as http://trusted.example@127.0.0.1/ can look like a trusted host to a naive prefix check. Other cases include backslashes in authority, decimal or hexadecimal IP forms, trailing dots, and DNS changes after validation. Assert that untrusted destinations never reach the network adapter.
At the application boundary, distinguish malformed syntax from failed validation. A syntactically sound https://example.com.au can still be disallowed by a tenant policy; an invalid postcode can be rejected by a request model rather than the URI library. Check that error responses do not echo credentials, internal addresses, stack traces, or raw parser diagnostics. Logging should use a bounded, redacted representation so hostile input cannot flood the pipeline.
Australian fixtures make the suite more representative. Teams in Sydney and Melbourne often use .com.au hosts; postcodes include Sydney’s 2000, Melbourne’s 3000, and Darwin’s leading-zero 0800; phone values may use the +61 country prefix; and place paths may contain Unicode such as /cafés/adelaide. These are valid domain data, so test them as encoding and validation cases rather than labelling them malformed. A parser test must remain independent of Australia’s public-suffix and postcode rules.
In the Australian market, Atlassian’s Sydney origins make Bitbucket Pipelines a familiar option for organisations standardised on its tooling, while GitHub-hosted runners are also common. A build described as “good to go” in a local stand-up still needs meaningful assertions. Run the suite across supported JDK versions, keep network access disabled for unit tests, and add integration tests where URL resolution or redirects are part of the contract. Coverage can reveal which parser branches were exercised, but line percentage alone does not prove malformed inputs were handled safely. The SonarQube CI coverage guide explains how to combine coverage evidence with test-analysis views.
Keep the parsing contract explicit
| Concern | java.net.URI |
java.net.URL |
Assertion focus |
|---|---|---|---|
| Syntax | Performs strict syntax checks and commonly raises URISyntaxException |
Legacy parsing is more permissive; unknown protocols raise MalformedURLException |
Assert each API’s documented failure rather than equivalence |
| Relative references | Valid as relative URIs | Does not represent a complete URL locator | Check isAbsolute() before URL conversion |
| Authority | Can represent authorities whose host cannot be parsed | Provides host-oriented access but follows legacy parsing rules | Compare raw and parsed authority components |
| Percent encoding | Detects malformed % sequences |
May retain invalid escapes in stored paths | Reject invalid encodings before downstream use |
| Network access | Construction performs no DNS lookup | Construction performs no connection or DNS lookup | Keep resolution in controlled integration tests |
Malformed URI and URL testing works best when each layer has an explicit contract. The parser answers whether it can represent a string; validation answers whether the represented value is allowed; downstream code answers whether it can be fetched, redirected, or logged safely. Keeping those decisions separate prevents a permissive parser from masking a strict policy and prevents a strict parser from being mistaken for complete input validation.
The behaviour worth remembering is simple: test malformed syntax, ambiguous authority, encoding boundaries, and rejected destinations as ordinary data with deterministic outcomes. A useful Java test suite proves both that unsafe values are refused and that refusal happens before they can trigger a network request, leak internals, or alter the meaning of a trusted host.