BAEL-5210 JUnit fail assertions use cases (#11314)

Co-authored-by: Andres Luzuriaga <aluzuriaga@proofpoint.com>
This commit is contained in:
andresluzu 2021-10-11 19:00:54 -05:00 committed by GitHub
parent 3cee038dfe
commit 8dce57b64f
2 changed files with 122 additions and 0 deletions

View File

@ -0,0 +1,72 @@
package com.baeldung.junit;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Random;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
public class FailAssertionUnitTest {
public static final Random RANDOM = new Random();
@Test
@Ignore
public void incompleteTest() {
fail("Not yet implemented");
}
@Test
public void expectedException() {
try {
methodThrowsException();
fail("Expected exception was not thrown");
} catch (Exception e) {
assertNotNull(e);
}
}
@Test
public void unexpectedException() {
try {
safeMethod();
// more testing code
} catch (Exception e) {
fail("Unexpected exception was thrown");
}
}
@Test
public void testingCondition() {
int result = randomInteger();
if (result > Integer.MAX_VALUE) {
fail("Result cannot exceed integer max value");
}
// more testing code
}
@Test
public void returnBefore() {
int value = randomInteger();
for (int i = 0; i < 5; i++) {
// returns when (value + i) is an even number
if ((i + value) % 2 == 0) {
return;
}
}
fail("Should have returned before");
}
private void safeMethod() {
}
private void methodThrowsException() throws Exception {
throw new Exception();
}
private int randomInteger() {
return RANDOM.nextInt(Integer.MAX_VALUE);
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.fail;
public class FailAssertionUnitTest {
@Test
void failThrowable() {
try {
safeMethod();
// more testing code
} catch (Exception e) {
fail(e);
}
}
@Test
void failMessageThrowable() {
try {
safeMethod();
// more testing code
} catch (Exception e) {
fail("Unexpected exception was thrown", e);
}
}
@Test
@Disabled
void failMessageSupplier() {
Supplier<String> timedMessage = () -> DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now());
fail(timedMessage);
}
@Test
void genericType() {
Stream.of().map(entry -> fail("should not be called"));
}
private void safeMethod() {
return;
}
}