Throw and throws in Java (#4990)
This commit is contained in:
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user