#62 added missing tests

This commit is contained in:
Fabio Formosa
2022-11-29 20:29:55 +01:00
parent fedb2b50b6
commit b17d487c8b
2 changed files with 38 additions and 6 deletions

View File

@@ -2,25 +2,29 @@ package it.fabioformosa.quartzmanager.api.common.utils;
import java.util.function.Function; import java.util.function.Function;
/**
*
* @param <R> success type
*/
public class Try<R> { public class Try<R> {
private final Throwable failure; private final Throwable failure;
private final R success; private final R success;
public Try(Throwable failure, R success) { private Try(Throwable failure, R success) {
this.failure = failure; this.failure = failure;
this.success = success; this.success = success;
} }
public R getSuccess() { private R getSuccess() {
return success; return success;
} }
public static <R> Try<R> success(R r){ private static <R> Try<R> success(R r){
return new Try<>(null, r); return new Try<>(null, r);
} }
public static <R> Try<R> failure(Throwable e){ private static <R> Try<R> failure(Throwable e){
return new Try<>(e, null); return new Try<>(e, null);
} }
@@ -38,11 +42,11 @@ public class Try<R> {
return t -> Try.with(checkedFunction).apply(t).getSuccess(); return t -> Try.with(checkedFunction).apply(t).getSuccess();
} }
public boolean isSuccess(){ private boolean isSuccess(){
return this.failure == null; return this.failure == null;
} }
public boolean isFailure(){ private boolean isFailure(){
return this.failure != null; return this.failure != null;
} }

View File

@@ -0,0 +1,28 @@
package it.fabioformosa.quartzmanager.api.common.utils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Optional;
class TryTest {
String raiseExceptionIfHello(String greetings) throws Exception {
if("hello".equals(greetings))
throw new Exception("hello");
return greetings;
}
@Test
void givenAFunction_whenItRaisesAnException_thenItReturnsNull(){
String hello = Optional.of("hello").map(Try.sneakyThrow(this::raiseExceptionIfHello)).orElse(null);
Assertions.assertThat(hello).isNull();
}
@Test
void givenAFunction_whenItDoesntRaisesAnException_thenItReturnsTheValue(){
String hello = Optional.of("not hello").map(Try.sneakyThrow(this::raiseExceptionIfHello)).orElse(null);
Assertions.assertThat(hello).isEqualTo("not hello");
}
}