This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,15 @@
package com.baeldung.junit5vstestng;
public class Calculator {
public double divide(double a, double b) {
if (b == 0) {
throw new DivideByZeroException("Divider cannot be equal to zero!");
}
return a/b;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.junit5vstestng;
public class DivideByZeroException extends RuntimeException {
public DivideByZeroException(String message) {
super(message);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.junit4;
import com.baeldung.junit4.categories.Annotations;
import com.baeldung.junit4.categories.JUnit4UnitTest;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(value = { Annotations.class, JUnit4UnitTest.class })
public class AnnotationTestExampleUnitTest {
@Test(expected = Exception.class)
public void shouldRaiseAnException() throws Exception {
throw new Exception("This is my expected exception");
}
@Test(timeout = 1)
@Ignore
public void shouldFailBecauseTimeout() throws InterruptedException {
Thread.sleep(10);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.junit4;
import org.junit.Assert;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
@DisplayName("Test case for assertions")
public class AssertionUnitTest {
@Test
@DisplayName("Arrays should be equals")
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals("Arrays should be equal", expected, actual);
}
@Test
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
assertEquals("4 is 2 times 2", 4, 2 * 2);
assertEquals("java", "JAVA".toLowerCase());
assertEquals("null is equal to null", null, null);
}
@Test
public void testAssertThatHasItems() {
assertThat(Arrays.asList("Java", "Kotlin", "Scala"), hasItems("Java", "Kotlin"));
}
}
@@ -0,0 +1,23 @@
package com.baeldung.junit4;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
public class AssumeUnitTest {
@Test
public void trueAssumption() {
assumeTrue("5 is greater the 1", 5 > 1);
assertEquals(5 + 2, 7);
}
@Test
public void falseAssumption() {
assumeFalse("5 is less then 1", 5 < 1);
assertEquals(5 + 2, 7);
}
}
@@ -0,0 +1,24 @@
package com.baeldung.junit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ExceptionAssertionUnitTest {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test(expected = NullPointerException.class)
public void whenExceptionThrown_thenExpectationSatisfied() {
String test = null;
test.length();
}
@Test
public void whenExceptionThrown_thenRuleIsApplied() {
exceptionRule.expect(NumberFormatException.class);
exceptionRule.expectMessage("For input string");
Integer.parseInt("1a");
}
}
@@ -0,0 +1,16 @@
package com.baeldung.junit4;
import org.junit.Rule;
import org.junit.Test;
public class RuleExampleUnitTest {
@Rule
public final TraceUnitTestRule traceRuleTests = new TraceUnitTestRule();
@Test
public void whenTracingTests() {
System.out.println("This is my test");
/*...*/
}
}
@@ -0,0 +1,34 @@
package com.baeldung.junit4;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import java.util.logging.Logger;
public class TestAnnotationsUnitTest {
private static final Logger log = Logger.getLogger(TestAnnotationsUnitTest.class.getName());
@BeforeClass
static void setup() {
log.info("@BeforeAll - executes once before all test methods in this class");
}
@Before
void init() {
log.info("@BeforeEach - executes before each test method in this class");
}
@After
void tearDown() {
log.info("@AfterEach - executed after each test method.");
}
@AfterClass
static void done() {
log.info("@AfterAll - executed after all test methods.");
}
}
@@ -0,0 +1,35 @@
package com.baeldung.junit4;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
import java.util.ArrayList;
import java.util.List;
public class TraceUnitTestRule implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
System.out.println("Starting test ... " + description.getMethodName());
try {
base.evaluate();
} catch (Throwable e) {
errors.add(e);
} finally {
System.out.println("... test finished. " + description.getMethodName());
}
MultipleFailureException.assertEmpty(errors);
}
};
}
}
@@ -0,0 +1,5 @@
package com.baeldung.junit4.categories;
public interface Annotations {
}
@@ -0,0 +1,5 @@
package com.baeldung.junit4.categories;
public interface JUnit4UnitTest {
}
@@ -0,0 +1,22 @@
package com.baeldung.junit4vstestng;
import static org.junit.Assert.assertTrue;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SortedUnitTest {
@Test
public void a_givenString_whenChangedtoInt_thenTrue() {
assertTrue(Integer.valueOf("10") instanceof Integer);
}
@Test
public void b_givenInt_whenChangedtoString_thenTrue() {
assertTrue(String.valueOf(10) instanceof String);
}
}
@@ -0,0 +1,58 @@
package com.baeldung.junit4vstestng;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class SummationServiceIntegrationTest {
private static List<Integer> numbers;
@BeforeClass
public static void initialize() {
numbers = new ArrayList<>();
}
@AfterClass
public static void tearDown() {
numbers = null;
}
@Before
public void runBeforeEachTest() {
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@After
public void runAfterEachTest() {
numbers.clear();
}
@Test
public void givenNumbers_sumEquals_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
@Ignore
@Test
public void givenEmptyList_sumEqualsZero_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
@Test(expected = ArithmeticException.class)
public void givenNumber_whenThrowsException_thenCorrect() {
int i = 1 / 0;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import java.time.Duration;
@Tag("annotations")
@Tag("junit5")
@RunWith(JUnitPlatform.class)
public class AnnotationTestExampleUnitTest {
@Test
public void shouldRaiseAnException() throws Exception {
Assertions.assertThrows(Exception.class, () -> {
throw new Exception("This is my expected exception");
});
}
@Test
@Disabled
public void shouldFailBecauseTimeout() throws InterruptedException {
Assertions.assertTimeout(Duration.ofMillis(1), () -> Thread.sleep(10));
}
}
@@ -0,0 +1,40 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DisplayName("Test case for assertions")
public class AssertionUnitTest {
@Test
@DisplayName("Arrays should be equals")
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals(expected, actual, "Arrays should be equal");
}
@Test
@DisplayName("The area of two polygons should be equal")
public void whenAssertingEquality_thenEqual() {
float square = 2 * 2;
float rectangle = 2 * 2;
assertEquals(square, rectangle);
}
@Test
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
assertAll(
"heading",
() -> assertEquals(4, 2 * 2, "4 is 2 times 2"),
() -> assertEquals("java", "JAVA".toLowerCase()),
() -> assertEquals((String) null, (String) null, "null is equal to null")
);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.*;
public class AssumptionUnitTest {
@Test
public void trueAssumption() {
assumeTrue(5 > 1, () -> "5 is greater the 1");
assertEquals(5 + 2, 7);
}
@Test
public void falseAssumption() {
assumeFalse(5 < 1, () -> "5 is less then 1");
assertEquals(5 + 2, 7);
}
@Test
public void assumptionThat() {
String someString = "Just a string";
assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4));
}
}
@@ -0,0 +1,69 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.*;
import static org.junit.jupiter.api.Assertions.*;
public class ConditionalExecutionUnitTest {
@Test
@EnabledOnOs({OS.MAC})
void whenOperatingSystemIsMac_thenTestIsEnabled() {
assertEquals(5 + 2, 7);
}
@Test
@DisabledOnOs({OS.WINDOWS})
void whenOperatingSystemIsWindows_thenTestIsDisabled() {
assertEquals(5 + 2, 7);
}
@Test
@EnabledOnJre({JRE.JAVA_8})
void whenRunningTestsOnJRE8_thenTestIsEnabled() {
assertTrue(5 > 4, "5 is greater the 4");
assertTrue(null == null, "null is equal to null");
}
@Test
@DisabledOnJre({JRE.JAVA_10})
void whenRunningTestsOnJRE10_thenTestIsDisabled() {
assertTrue(5 > 4, "5 is greater the 4");
assertTrue(null == null, "null is equal to null");
}
@Test
@EnabledIfSystemProperty(named = "os.arch", matches = ".*64.*")
public void whenRunningTestsOn64BitArchitectures_thenTestIsDisabled() {
Integer value = 5; // result of an algorithm
assertNotEquals(0, value, "The result cannot be 0");
}
@Test
@DisabledIfSystemProperty(named = "ci-server", matches = "true")
public void whenRunningTestsOnCIServer_thenTestIsDisabled() {
Integer value = 5; // result of an algorithm
assertNotEquals(0, value, "The result cannot be 0");
}
@Test
@EnabledIfEnvironmentVariable(named = "ENV", matches = "staging-server")
public void whenRunningTestsStagingServer_thenTestIsEnabled() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals(expected, actual, "Arrays should be equal");
}
@Test
@DisabledIfEnvironmentVariable(named = "ENV", matches = ".*development.*")
public void whenRunningTestsDevelopmentEnvironment_thenTestIsDisabled() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals(expected, actual, "Arrays should be equal");
}
}
@@ -0,0 +1,77 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.*;
import java.util.EmptyStackException;
import java.util.Stack;
public class NestedUnitTest {
Stack<Object> stack;
@Test
@DisplayName("is instantiated with new Stack()")
void isInstantiatedWithNew() {
new Stack<>();
}
@Nested
@DisplayName("when new")
class WhenNew {
@BeforeEach
void init() {
stack = new Stack<>();
}
@Test
@DisplayName("is empty")
void isEmpty() {
Assertions.assertTrue(stack.isEmpty());
}
@Test
@DisplayName("throws EmptyStackException when popped")
void throwsExceptionWhenPopped() {
Assertions.assertThrows(EmptyStackException.class, () -> stack.pop());
}
@Test
@DisplayName("throws EmptyStackException when peeked")
void throwsExceptionWhenPeeked() {
Assertions.assertThrows(EmptyStackException.class, () -> stack.peek());
}
@Nested
@DisplayName("after pushing an element")
class AfterPushing {
String anElement = "an element";
@BeforeEach
void init() {
stack.push(anElement);
}
@Test
@DisplayName("it is no longer empty")
void isEmpty() {
Assertions.assertFalse(stack.isEmpty());
}
@Test
@DisplayName("returns the element when popped and is empty")
void returnElementWhenPopped() {
Assertions.assertEquals(anElement, stack.pop());
Assertions.assertTrue(stack.isEmpty());
}
@Test
@DisplayName("returns the element when peeked but remains not empty")
void returnElementWhenPeeked() {
Assertions.assertEquals(anElement, stack.peek());
Assertions.assertFalse(stack.isEmpty());
}
}
}
}
@@ -0,0 +1,17 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@ExtendWith(TraceUnitExtension.class)
public class RuleExampleUnitTest {
@Test
public void whenTracingTests() {
System.out.println("This is my test");
/*...*/
}
}
@@ -0,0 +1,27 @@
package com.baeldung.junit5;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.ExpectedException;
@EnableRuleMigrationSupport
public class RuleMigrationSupportUnitTest {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test
public void whenExceptionThrown_thenExpectationSatisfied() {
exceptionRule.expect(NullPointerException.class);
String test = null;
test.length();
}
@Test
public void whenExceptionThrown_thenRuleIsApplied() {
exceptionRule.expect(NumberFormatException.class);
exceptionRule.expectMessage("For input string");
Integer.parseInt("1a");
}
}
@@ -0,0 +1,39 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.*;
import java.util.logging.Logger;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestAnnotationsUnitTest {
private static final Logger log = Logger.getLogger(TestAnnotationsUnitTest.class.getName());
@BeforeAll
static void setup() {
log.info("@BeforeAll - executes once before all test methods in this class");
}
@BeforeEach
void init() {
log.info("@BeforeEach - executes before each test method in this class");
}
@Test
@Disabled
void disabledTest() {
assertTrue(false);
}
@AfterEach
void tearDown() {
log.info("@AfterEach - executed after each test method.");
}
@AfterAll
static void done() {
log.info("@AfterAll - executed after all test methods.");
}
}
@@ -0,0 +1,19 @@
package com.baeldung.junit5;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
public class TraceUnitExtension implements AfterEachCallback, BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext context) throws Exception {
System.out.println("Starting test ... " + context.getDisplayName());
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
System.out.println("... test finished. " + context.getDisplayName());
}
}
@@ -0,0 +1,101 @@
package com.baeldung.junit5vsjunit4assertions;
import org.junit.Test;
import java.util.Arrays;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.Assert.*;
/**
* Unit test that demonstrate the different assertions available within JUnit 4
*/
public class Junit4AssertionsUnitTest {
@Test
public void whenAssertingEquality_thenEqual() {
String expected = "Baeldung";
String actual = "Baeldung";
assertEquals(expected, actual);
}
@Test
public void whenAssertingEqualityWithMessage_thenEqual() {
String expected = "Baeldung";
String actual = "Baeldung";
assertEquals("failure - strings are not equal", expected, actual);
}
@Test
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = { 'J', 'u', 'n', 'i', 't' };
char[] actual = "Junit".toCharArray();
assertArrayEquals(expected, actual);
}
@Test
public void givenNullArrays_whenAssertingArraysEquality_thenEqual() {
int[] expected = null;
int[] actual = null;
assertArrayEquals(expected, actual);
}
@Test
public void whenAssertingNull_thenTrue() {
Object car = null;
assertNull("The car should be null", car);
}
@Test
public void whenAssertingNotNull_thenTrue() {
Object car = new Object();
assertNotNull("The car should not be null", car);
}
@Test
public void whenAssertingNotSameObject_thenDifferent() {
Object cat = new Object();
Object dog = new Object();
assertNotSame(cat, dog);
}
@Test
public void whenAssertingSameObject_thenSame() {
Object cat = new Object();
assertSame(cat, cat);
}
@Test
public void whenAssertingConditions_thenVerified() {
assertTrue("5 is greater then 4", 5 > 4);
assertFalse("5 is not greater then 6", 5 > 6);
}
@Test
public void when_thenNotFailed() {
try {
methodThatShouldThrowException();
fail("Exception not thrown");
} catch (UnsupportedOperationException e) {
assertEquals("Operation Not Supported", e.getMessage());
}
}
private void methodThatShouldThrowException() {
throw new UnsupportedOperationException("Operation Not Supported");
}
@Test
public void testAssertThatHasItems() {
assertThat(Arrays.asList("Java", "Kotlin", "Scala"), hasItems("Java", "Kotlin"));
}
}
@@ -0,0 +1,192 @@
package com.baeldung.junit5vsjunit4assertions;
import static java.time.Duration.ofSeconds;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Unit test that demonstrate the different assertions available within JUnit 4
*/
@DisplayName("Test case for assertions")
public class Junit5AssertionsUnitTest {
@Test
@DisplayName("Arrays should be equals")
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals(expected, actual, "Arrays should be equal");
}
@Test
@DisplayName("The area of two polygons should be equal")
public void whenAssertingEquality_thenEqual() {
float square = 2 * 2;
float rectangle = 2 * 2;
assertEquals(square, rectangle);
}
@Test
public void whenAssertingEqualityWithDelta_thenEqual() {
float square = 2 * 2;
float rectangle = 3 * 2;
float delta = 2;
assertEquals(square, rectangle, delta);
}
@Test
public void whenAssertingConditions_thenVerified() {
assertTrue(5 > 4, "5 is greater the 4");
assertTrue(null == null, "null is equal to null");
}
@Test
public void whenAssertingNull_thenTrue() {
Object cat = null;
assertNull(cat, () -> "The cat should be null");
}
@Test
public void whenAssertingNotNull_thenTrue() {
Object dog = new Object();
assertNotNull(dog, () -> "The dog should not be null");
}
@Test
public void whenAssertingSameObject_thenSuccessfull() {
String language = "Java";
Optional<String> optional = Optional.of(language);
assertSame(language, optional.get());
}
@Test
public void givenBooleanSupplier_whenAssertingCondition_thenVerified() {
BooleanSupplier condition = () -> 5 > 6;
assertFalse(condition, "5 is not greater then 6");
}
@Test
@Disabled
public void whenFailingATest_thenFailed() {
// Test not completed
fail("FAIL - test not completed");
}
@Test
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
Object obj = null;
assertAll(
"heading",
() -> assertEquals(4, 2 * 2, "4 is 2 times 2"),
() -> assertEquals("java", "JAVA".toLowerCase()),
() -> assertEquals(obj, null, "null is equal to null")
);
}
@Test
public void givenTwoLists_whenAssertingIterables_thenEquals() {
Iterable<String> al = new ArrayList<>(asList("Java", "Junit", "Test"));
Iterable<String> ll = new LinkedList<>(asList("Java", "Junit", "Test"));
assertIterableEquals(al, ll);
}
@Test
public void whenAssertingTimeout_thenNotExceeded() {
assertTimeout(
ofSeconds(2),
() -> {
// code that requires less then 2 minutes to execute
Thread.sleep(1000);
}
);
}
@Test
public void whenAssertingTimeoutPreemptively_thenNotExceeded() {
assertTimeoutPreemptively(
ofSeconds(2),
() -> {
// code that requires less then 2 minutes to execute
Thread.sleep(1000);
}
);
}
@Test
public void whenAssertingEquality_thenNotEqual() {
Integer value = 5; // result of an algorithm
assertNotEquals(0, value, "The result cannot be 0");
}
@Test
public void whenAssertingEqualityListOfStrings_thenEqual() {
List<String> expected = asList("Java", "\\d+", "JUnit");
List<String> actual = asList("Java", "11", "JUnit");
assertLinesMatch(expected, actual);
}
@Test
void whenAssertingException_thenThrown() {
Throwable exception = assertThrows(
IllegalArgumentException.class,
() -> {
throw new IllegalArgumentException("Exception message");
}
);
assertEquals("Exception message", exception.getMessage());
}
@Test
public void testConvertToDoubleThrowException() {
String age = "eighteen";
assertThrows(NumberFormatException.class, () -> {
convertToInt(age);
});
assertThrows(NumberFormatException.class, () -> {
convertToInt(age);
});
}
private static Integer convertToInt(String str) {
if (str == null) {
return null;
}
return Integer.valueOf(str);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.junit5vstestng;
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,15 @@
package com.baeldung.junit5vstestng;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
public class Class1UnitTest {
@Test
public void testCase_InClass1UnitTest() {
assertTrue(true);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.junit5vstestng;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
public class Class2UnitTest {
@Test
public void testCase_InClass2UnitTest() {
assertTrue(true);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.junit5vstestng;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class CustomNameUnitTest {
@ParameterizedTest
@ValueSource(strings = { "Hello", "World" })
@DisplayName("Test Method to check that the inputs are not nullable")
void givenString_TestNullOrNot(String word) {
assertNotNull(word);
}
}
@@ -0,0 +1,45 @@
package com.baeldung.junit5vstestng;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.EnumSet;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
public class ParameterizedUnitTest {
@ParameterizedTest
@ValueSource(strings = { "Hello", "World" })
void givenString_TestNullOrNot(String word) {
assertNotNull(word);
}
@ParameterizedTest
@EnumSource(value = PizzaDeliveryStrategy.class, names = {"EXPRESS", "NORMAL"})
void givenEnum_TestContainsOrNot(PizzaDeliveryStrategy timeUnit) {
assertTrue(EnumSet.of(PizzaDeliveryStrategy.EXPRESS, PizzaDeliveryStrategy.NORMAL).contains(timeUnit));
}
@ParameterizedTest
@MethodSource("wordDataProvider")
void givenMethodSource_TestInputStream(String argument) {
assertNotNull(argument);
}
static Stream<String> wordDataProvider() {
return Stream.of("foo", "bar");
}
@ParameterizedTest
@CsvSource({ "1, Car", "2, House", "3, Train" })
void givenCSVSource_TestContent(int id, String word) {
assertNotNull(id);
assertNotNull(word);
}
}
@@ -0,0 +1,6 @@
package com.baeldung.junit5vstestng;
public enum PizzaDeliveryStrategy {
EXPRESS,
NORMAL;
}
@@ -0,0 +1,11 @@
package com.baeldung.junit5vstestng;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@SelectClasses({Class1UnitTest.class, Class2UnitTest.class})
public class SelectClassesSuiteUnitTest {
}
@@ -0,0 +1,11 @@
package com.baeldung.junit5vstestng;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@SelectPackages({ "org.baeldung.java.suite.childpackage1", "org.baeldung.java.suite.childpackage2" })
public class SelectPackagesSuiteUnitTest {
}
@@ -0,0 +1,53 @@
package com.baeldung.junit5vstestng;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class SummationServiceUnitTest {
private static List<Integer> numbers;
@BeforeAll
public static void initialize() {
numbers = new ArrayList<>();
}
@AfterAll
public static void tearDown() {
numbers = null;
}
@BeforeEach
public void runBeforeEachTest() {
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@AfterEach
public void runAfterEachTest() {
numbers.clear();
}
@Test
public void givenNumbers_sumEquals_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
@Ignore
@Test
public void givenEmptyList_sumEqualsZero_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
}