Skip to content

Instantly share code, notes, and snippets.

@RDayal11
Created April 14, 2022 19:10
Show Gist options
  • Save RDayal11/dd04b8f4a46dfe63fa799d319ec471d6 to your computer and use it in GitHub Desktop.
Save RDayal11/dd04b8f4a46dfe63fa799d319ec471d6 to your computer and use it in GitHub Desktop.
package LambdaTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class handlingExceptionsUsingJUnit5 {
@Test
void whenNoExceptionIsThrown() {
NumberFormatException thrown = Assertions
.assertThrows(NumberFormatException.class, () -> {
Integer.parseInt("1");
}, "NumberFormatException error was expected, but no exception was thrown");
Assertions.assertEquals("Some expected message", thrown.getMessage());
}
@Test
void whenAdifferentExceptionIsThrown() {
NumberFormatException thrown = Assertions
.assertThrows(NumberFormatException.class, () -> {
int result = 3 / 0;
}, "NumberFormatException error was expected, but a different exception was thrown");
Assertions.assertEquals("Some expected message", thrown.getMessage());
}
@Test
void whenTheSameExceptionIsThrown() {
NumberFormatException thrown = Assertions.assertThrows(NumberFormatException.class, () -> {
Integer.parseInt("One");
}, "NumberFormatException is expected");
Assertions.assertEquals("For input string: \"One\"", thrown.getMessage());
}
@Test
void whenParentExceptionIsThrown() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
Integer.parseInt("One");
});
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>LambdaTest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-suite</artifactId>
<version>1.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment