Quick revision
The short answer
We can expect the exception with @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = ".*amount.*"), or more precisely with Assert.expectThrows(IllegalArgumentException.class, () -> transfer(-5)) followed by an assertion on the message. For the time limit, @Test(timeOut = 2000) fails the test if loadConfig() runs longer than 2000 milliseconds, but it runs the method in a separate thread, so thread-bound state such as a Spring test transaction is not shared with it.
What to remember
In this answer, we wrote an exception test with expectedExceptions and expectedExceptionsMessageRegExp, saw that it passes if any line of the method throws, and rewrote it with Assert.expectThrows so the check covers only transfer(-5) and the message can be asserted directly. We then wrote a test with timeOut = 2000 and saw that TestNG runs such a method on a separate thread, which means thread-bound state like a Spring transaction does not reach it.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We can expect the exception with @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = ".*amount.*"), or more precisely with Assert.expectThrows(IllegalArgumentException.class, () -> transfer(-5)) followed by an assertion on the message. For the time limit, @Test(timeOut = 2000) fails the test if loadConfig() runs longer than 2000 milliseconds, but it runs the method in a separate thread, so thread-bound state such as a Spring test transaction is not shared with it.
Why this question is asked
Checking that code fails correctly is as important as checking that it works, and slow configuration loading is a classic source of startup problems, so this pair of small tests comes up often. Interviewers use it to see whether we know both styles of exception testing in TestNG, which one is safer, and what the timeOut attribute really does under the hood. In this answer, we will write the exception test with the annotation, see the case where the annotation passes for the wrong reason, rewrite it with expectThrows, write the timeout test, and then look at the threading detail that surprises many people.
1A Quick Recap of the Method Under Test
Suppose transfer(amount) belongs to an AccountService and should reject a negative amount. A good implementation throws IllegalArgumentException, the standard Java exception for an argument that breaks the method's rules, with a message that names the problem.
Our test should prove two things: that the right type of exception is thrown, and that its message mentions amount, so a user or a log reader can tell what went wrong.
2The Annotation Style: expectedExceptions
TestNG lets us declare the expected exception on the @Test annotation itself. The test passes only if the method throws an exception of that type, or a subclass, and fails if it returns normally. The optional expectedExceptionsMessageRegExp attribute is a regular expression that the whole message must match.
Notice the .* on both sides of amount. The regular expression must match the entire message, not just a part of it, so "amount" on its own would fail against our message. The default value of the attribute is .*, which accepts any message.
3When the Annotation Passes for the Wrong Reason
But there is a catch: the annotation applies to the whole method. If any line of the method throws an IllegalArgumentException with a matching message, the test passes, even if it is not the line we meant to test.
Currency.getInstance throws IllegalArgumentException for an unknown code, so the test passes during setup and never reaches transfer(). A bug in transfer() would not be noticed. That is the reason most teams prefer to check the exact statement.
4The Precise Style: Assert.expectThrows
TestNG's Assert class has two methods for this. assertThrows(type, runnable) checks that the code throws the given type and returns nothing. expectThrows(type, runnable) does the same and returns the exception, so we can make further assertions on it. Both take a lambda, which limits the check to exactly the code inside it.
| Aspect | expectedExceptions attribute | Assert.expectThrows |
|---|---|---|
| Scope of the check | Any line of the method | Only the code in the lambda |
| Message check | Regular expression on the whole message | Any assertion on the returned exception |
| Code after the throw | Cannot run | Can check state after the failure |
| Wrong line throwing | Test passes silently | Test fails |
Now a failure during setup is reported as a failure, not a pass, because it happens outside the lambda. The message check is a plain contains() instead of a regular expression, which is easier to read, and passing e.getMessage() as the assertion message prints the real text if the check fails.
5Failing a Test That Runs Longer Than 2 Seconds
For the time limit, the timeOut attribute takes a number of milliseconds. If the method has not finished within that time, TestNG marks it as failed with a timeout error.
TestNG also has invocationTimeOut, which limits the total time of all invocations when a test runs several times with invocationCount. For a single call, timeOut is the one we want.
6Why timeOut Runs the Method in Another Thread
To stop waiting after 2000 milliseconds, TestNG cannot simply call the method on the current thread, because then it would have to wait for it. Instead it hands the method to a separate worker thread and waits on that thread with a time limit. If the limit passes, TestNG reports the failure and tries to interrupt the worker.
Notice two consequences. First, anything bound to the test thread through a ThreadLocal, a variable that each thread sees its own copy of, is not visible inside the test method. A Spring test transaction started by @Transactional, the Spring Security context and the logging MDC all work this way, so the method runs outside them. Second, a method that ignores interrupts, such as one blocked on a socket read without a timeout, may keep running in the background after the test has already failed. So we use timeOut for plain code that might hang, and not for tests that rely on thread-bound context.
5 messages in order. Play them, or step through them one at a time.
The test method never runs on the thread that ran @BeforeMethod.
7Follow-up questions
Why prefer expectThrows over the expectedExceptions attribute?
Because it checks exactly one statement. The attribute passes if any line in the method throws the expected type, including setup code, so it can hide bugs. expectThrows also returns the exception, so we can assert on its message, its cause or the object's state afterwards, which the annotation style cannot do because the method stops at the throw.
Does expectedExceptions accept subclasses of the declared type?
Yes. Declaring IllegalArgumentException also accepts NumberFormatException, which extends it. The same is true for expectThrows. If the exact type matters, we can assert on e.getClass() after expectThrows.
Is a timeOut test a good performance test?
Not really. It only says the call finished within a generous limit on one machine, and CI machines vary a lot in speed, so tight limits cause flaky failures. It is good as a guard against code that hangs. For real performance numbers, we use a benchmark tool such as JMH or measurements in a performance environment.
8Conclusion
In this answer, we wrote an exception test with expectedExceptions and expectedExceptionsMessageRegExp, saw that it passes if any line of the method throws, and rewrote it with Assert.expectThrows so the check covers only transfer(-5) and the message can be asserted directly. We then wrote a test with timeOut = 2000 and saw that TestNG runs such a method on a separate thread, which means thread-bound state like a Spring transaction does not reach it.
Open with
For the exception, the quick version is @Test with expectedExceptions set to IllegalArgumentException.class and expectedExceptionsMessageRegExp set to dot star amount dot star, with the body just calling transfer of minus five.
Then, if they want more
The regular expression has to match the whole message, which is why I wrap amount in dot star. I prefer the explicit version though: IllegalArgumentException e equals Assert.expectThrows, passing the class and a lambda that calls transfer of minus five, then assertTrue that e.getMessage contains amount.
The difference matters because the annotation passes if any line of the method throws that exception, including setup code, so a test can pass without ever reaching transfer. expectThrows only checks the code inside the lambda, and it gives me the exception so I can assert on the message or the cause.
For the timeout, I write @Test with timeOut equal to 2000 on a method that calls loadConfig. If the method has not finished after 2000 milliseconds, TestNG fails it with a timeout error. One thing to know is that TestNG runs a timeOut method on a separate worker thread so it can stop waiting.
That means anything stored in thread locals, like a Spring test transaction, the security context or the MDC, is not visible in the test method, so I would not put timeOut on a transactional Spring test.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- JUnit user guide, Mockito documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "In TestNG, write a test that expects an IllegalArgumentException with a message...": https://scrivio-interview-library.netlify.app/java/testng/6158c9e034/