Java junit check exception

JUnit Test Exception Examples — How to assert an exception is thrown

In this JUnit tutorial, you will learn how to assert an exception is thrown by the code under test. Suppose that we want to test the exception thrown by the setName() method in the User class below:

package net.codejava; public class User < private String name; public void setName(String name) < if (name == null) < throw new IllegalArgumentException("Username cannot be blank"); >else < if (name.length() < 3) < throw new IllegalArgumentException("Username is too short"); >else if (name.length() > 30) < throw new IllegalArgumentException("Username is too long"); >> this.name = name; > >

1. Test Exception in JUnit 5 — using assertThrows() method

JUnit 5 provides the assertThrows() method that asserts a piece of code throws an exception of an expected type and returns the exception:

assertThrows(Class expectedType, Executable executable, String message)

You put the code that can throw exception in the execute() method of an Executable type — Executable is a functional interface defined by JUnit. The message is optional, to be included in the error message printed when the test fails.

Читайте также:  Opencv изменить размер изображения python

For example, the following test class implements a test method that asserts IllegalArgumentException is thrown by the setName() method of the User class:

package net.codejava; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; public class UserTest < @Test public void testUsernameIsNull() < assertThrows(IllegalArgumentException.class, new Executable() < @Override public void execute() throws Throwable < User user = new User(); user.setName(null); >>); > >

If the expected exception ( IllegalArgumentException in this example) is thrown, the test succeeded, otherwise it fails.

You can see the above code uses an anonymous class of type Executable . Of course you can shorter the code with Lambda syntax:

@Test public void testUsernameIsNull() < assertThrows(IllegalArgumentException.class, () ->< User user = new User(); user.setName(null); >); >
@Test public void testUsernameIsNull() < Throwable exception = assertThrows( IllegalArgumentException.class, () -> < User user = new User(); user.setName(null); >); assertEquals("Username cannot be blank", exception.getMessage()); >

Similarly, the following method tests the case username is too short:

@Test public void testUsernameTooShort() < Throwable exception = assertThrows( IllegalArgumentException.class, () -> < User user = new User(); user.setName("Jo"); >); assertEquals("Username is too short", exception.getMessage()); >

And the following method tests the case username is too long:

@Test public void testUsernameTooLong() < Throwable exception = assertThrows( IllegalArgumentException.class, () -> < User user = new User(); user.setName("Pablo Diego Jose Franciso Picasso"); >); assertEquals("Username is too long", exception.getMessage()); >

2. Test Exception in JUnit 4

In JUnit 4.7 or above, you can test exception by using the @Rule annotation with an ExpectedException class, for example:

package net.codejava; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class UserTest < @Rule public ExpectedException exception = ExpectedException.none(); @Test public void testUsernameTooShort() < exception.expect(IllegalArgumentException.class); exception.expectMessage("Username is too short"); User user = new User(); user.setName("Jo"); >>

The ExpectedException object is created as a rule that expects none exception is thrown so this rule doesn’t affect all existing test methods:

@Rule public ExpectedException exception = ExpectedException.none();

Then in the test method you can use its expect() and expectMessage() to assert the type of expected exception and the exception message.

In older versions of JUnit 4, you can specify the expected exception in the @Test annotation like this:

@Test(expected = IllegalArgumentException.class) public void testUsernameIsNull()

3. Test Exception in JUnit 3

In JUnit 3, or more exactly, in any versions of JUnit you can always use Java’s try-catch structure to test exception. Here’s an example:

package net.codejava; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; public class UserTest < @Test public void testUserNameTooShort() < try < User user = new User(); user.setName("Jo"); fail(); >catch (IllegalArgumentException ex) < assertEquals("Username is too short", ex.getMessage()); >> >

As you can see, we use the fail() statement at the end of the catch block so if the code doesn’t throw any exception, the test fails. And we catch the expected exception by the catch clause, in which we use assertEquals() methods to assert the exception message. You can use this structure to test any exceptions.

References:

Other JUnit Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Assert an Exception Is Thrown in JUnit 4 and 5

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Introduction

In this quick tutorial, we’ll be looking at how to test if an exception was thrown using the JUnit library.

We will, of course, make sure to cover both the JUnit 4 and JUnit 5 versions.

Further reading:

AssertJ Exception Assertions

Assertions in JUnit 4 and JUnit 5

Mocking Exception Throwing using Mockito

2. JUnit 5

JUnit 5 Jupiter assertions API introduces the assertThrows method for asserting exceptions.

This takes the type of the expected exception and an Executable functional interface where we can pass the code under test through a lambda expression:

@Test public void whenExceptionThrown_thenAssertionSucceeds() < Exception exception = assertThrows(NumberFormatException.class, () ->< Integer.parseInt("1a"); >); String expectedMessage = "For input string"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); >

If the expected exception is thrown, assertThrows returns the exception, which enables us to also assert on the message.

Furthermore, it’s important to note that this assertion is satisfied when the enclosed code throws an exception of type NumberFormatException or any of its derived types.

This means that if we pass Exception as the expected exception type, any exception thrown will make the assertion succeed since Exception is the super-type for all exceptions.

If we change the test above to expect a RuntimeException, this will also pass:

@Test public void whenDerivedExceptionThrown_thenAssertionSucceeds() < Exception exception = assertThrows(RuntimeException.class, () ->< Integer.parseInt("1a"); >); String expectedMessage = "For input string"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); >

The assertThrows() method enables more fine-grained control for exception assertion logic because we can use it around specific parts of the code.

3. JUnit 4

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method.

As a result, when the test is run, it will fail if the specified exception isn’t thrown and will pass if it’s thrown:

@Test(expected = NullPointerException.class) public void whenExceptionThrown_thenExpectationSatisfied()

In this example, we’ve declared that we’re expecting our test code to result in a NullPointerException.

This is enough if we’re only interested in asserting that an exception is thrown.

When we need to verify some other properties of the exception, we can use the ExpectedException rule.

Let’s see an example of verifying the message property of an exception:

@Rule public ExpectedException exceptionRule = ExpectedException.none(); @Test public void whenExceptionThrown_thenRuleIsApplied()

In the example above, we’re first declaring the ExpectedException rule. Then in our test, we’re asserting that the code that attempts to parse an Integer value will result in a NumberFormatException with the message “For input string”.

4. Conclusion

In this article, we covered asserting exceptions with both JUnit 4 and JUnit 5.

The full source code for the examples is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

how to handle exceptions in junit

I wrote some test cases to test some method. But some methods throw an exception. Am I doing it correctly?

private void testNumber(String word, int number) < try < assertEquals(word, service.convert(number)); >catch (OutOfRangeNumberException e) < Assert.fail("Test failed : " + e.getMessage()); >> @Test public final void testZero()

If I pass -45 , it will fail with OutOfRangeException but I am not able to test specific exception like @Test(Expected. )

4 Answers 4

An unexpected exception is a test failure, so you neither need nor want to catch one.

@Test public void canConvertStringsToDecimals()

Until service does not throw an IllegalArgumentException because str has a decimal point in it, that will be a simple test failure.

An expected exception should be handled by the optional expected argument of @Test .

@Test(expected=NullPointerException.class) public void cannotConvertNulls()

If the programmer was lazy and threw Exception , or if he had service return 0.0 , the test will fail. Only an NPE will succeed. Note that subclasses of the expected exception also work. That’s rare for NPE s, but common with IOException s and SQLException s.

In the rare case that you want to test for a specific exception message, you use the newish ExpectedException JUnit @Rule .

@Rule public ExpectedException thrown= ExpectedException.none(); @Test public void messageIncludesErrantTemperature() < thrown.expect(IllegalArgumentException.class); thrown.expectMessage("-400"); // Tests that the message contains -400. temperatureGauge.setTemperature(-400); >

Now, unless the setTemperature throws an IAE and the message contains the temperature the user was trying to set, the test fails. This rule can be used in more sophisticated ways.

Your example can best be handled by:

private void testNumber(String word, int number) throws OutOfRangeNumberException < assertEquals(word, service.convert(number)); >@Test public final void testZero() throws OutOfRangeNumberException

You can inline testNumber ; now, it does not help much. You can turn this into a parametrized test class.

Источник

Оцените статью