Testing / JUnit6 Interview Questions
What are parameterized tests in JUnit 6 and how do you write them?
Parameterized tests run the same test method multiple times with different arguments. In JUnit 6 they are written with @ParameterizedTest and a source annotation that provides the data.
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.*; class ParameterizedDemo { // @ValueSource: simple single-argument tests @ParameterizedTest @ValueSource(ints = {1, 2, 3, 4, 5}) void isPositive(int n) { assertTrue(n > 0); } // @CsvSource: multiple arguments per invocation @ParameterizedTest(name = "{index}: add({0}, {1}) = {2}") @CsvSource({ "1, 2, 3", "10, 20, 30", "-5, 5, 0" }) void additionTest(int a, int b, int expected) { assertEquals(expected, a + b); } // @MethodSource: call a static method returning a Stream @ParameterizedTest @MethodSource("provideStrings") void blankStringsAreRejected(String input) { assertThrows(IllegalArgumentException.class, () -> new Username(input)); } static Stream<String> provideStrings() { return Stream.of("", " ", " ", null); } // @EnumSource: test all or selected enum values @ParameterizedTest @EnumSource(value = Status.class, names = {"PENDING", "PROCESSING"}) void activeStatusesAreNotFinal(Status s) { assertFalse(s.isFinal()); } // @NullSource / @EmptySource / @NullAndEmptySource @ParameterizedTest @NullAndEmptySource void nullAndEmptyAreRejected(String input) { assertThrows(IllegalArgumentException.class, () -> new Username(input)); } }
JUnit 6 display name change: parameterized test names now consistently format arguments as name = value (with spaces around =) instead of JUnit 5's name=value. This affects CI report output and test filtering by name.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
