Throw and throws in Java (#4990)

This commit is contained in:
Kacper
2018-08-19 22:02:27 +02:00
committed by maibin
parent a21e940d8c
commit 9156ec3736
10 changed files with 198 additions and 0 deletions
@@ -0,0 +1,17 @@
package com.baeldung.throwsexception;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class CalculatorUnitTest {
@Test
public void whenDividerIsZero_thenDivideByZeroExceptionIsThrown() {
Calculator calculator = new Calculator();
assertThrows(DivideByZeroException.class,
() -> calculator.divide(10, 0));
}
}
@@ -0,0 +1,32 @@
package com.baeldung.throwsexception;
import org.junit.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PersonRepositoryUnitTest {
PersonRepository personRepository = new PersonRepository();
@Test
public void whenIdIsNull_thenExceptionIsThrown() throws Exception {
assertThrows(Exception.class,
() ->
Optional
.ofNullable(personRepository.findNameById(null))
.orElseThrow(Exception::new));
}
@Test
public void whenIdIsNonNull_thenNoExceptionIsThrown() throws Exception {
assertAll(
() ->
Optional
.ofNullable(personRepository.findNameById("id"))
.orElseThrow(Exception::new));
}
}
@@ -0,0 +1,22 @@
package com.baeldung.throwsexception;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SimpleServiceUnitTest {
SimpleService simpleService = new SimpleService();
@Test
void whenSQLExceptionIsThrown_thenShouldBeRethrownWithWrappedException() {
assertThrows(DataAccessException.class,
() -> simpleService.wrappingException());
}
@Test
void whenCalled_thenNullPointerExceptionIsThrown() {
assertThrows(NullPointerException.class,
() -> simpleService.runtimeNullPointerException());
}
}