Complete the code to create a JUnit test method that asserts two strings are equal.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.[1]; public class SampleTest { @Test void testStrings() { String expected = "hello"; String actual = "hello"; [1](expected, actual); } }
The assertEquals method checks if two values are equal, which is what we want to test here.
Complete the code to create a dynamic test name using JUnit 5's @DisplayName annotation.
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.DisplayName; public class DynamicNameTest { @Test @DisplayName("Test for user: [1]") void testUser() { // test code here } }
The @DisplayName annotation requires a string literal, so the user name must be in quotes.
Fix the error in the code to correctly implement a dynamic test with JUnit 5's @TestFactory.
import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; public class DynamicTests { @TestFactory Stream<DynamicTest> dynamicTests() { return Stream.of( DynamicTest.dynamicTest("Test 1", () -> [1]) ); } }
The lambda must contain a valid assertion. assertEquals(2, 1 + 1) correctly asserts that 1 + 1 equals 2.
Fill both blanks to create a parameterized test method that uses @ValueSource with integers.
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.[1]; public class ParamTest { @ParameterizedTest @[2](ints = {1, 2, 3}) void testNumbers(int number) { // test code } }
The @ValueSource annotation is used to provide primitive values like integers to parameterized tests.
Fill all three blanks to create a dynamic test stream that tests if strings are not empty.
import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertTrue; public class StringTests { @TestFactory Stream<DynamicTest> dynamicTestsForStrings() { String[] inputs = {"apple", "", "banana"}; return Stream.of(inputs).map(input -> DynamicTest.dynamicTest("Test: " + input, () -> { [1].assertTrue(!input.[2](), "String is empty"); }) ); } }
We use Assertions.assertTrue to check that the string is not empty by calling input.isEmpty().