Testing / JUnit6 Interview Questions
What are test interfaces and default methods in JUnit 6?
JUnit 6 supports placing @Test, @BeforeEach, @AfterEach, and other annotations on interface default methods. Test classes implementing the interface automatically inherit those tests and lifecycle methods. This is useful for contract testing and shared test behaviour.
// Define a reusable contract test as an interface public interface ComparableContract<T extends Comparable<T>> { T createEqualValue(); T createSmallerValue(); T createLargerValue(); @Test default void reflexive() { T val = createEqualValue(); assertEquals(0, val.compareTo(createEqualValue())); } @Test default void symmetricForEqual() { T a = createEqualValue(); T b = createEqualValue(); assertEquals(0, a.compareTo(b)); assertEquals(0, b.compareTo(a)); } @Test default void smallerIsLessThanLarger() { assertTrue(createSmallerValue().compareTo(createLargerValue()) < 0); } } // Implementing classes get all contract tests for free: class StringComparableTest implements ComparableContract<String> { @Override public String createEqualValue() { return "hello"; } @Override public String createSmallerValue() { return "apple"; } @Override public String createLargerValue() { return "zebra"; } // Also free to add class-specific @Test methods @Test void stringsAreCaseSensitive() { assertNotEquals(0, "Hello".compareTo("hello")); } } // Any class implementing ComparableContract gets all 3 contract tests.
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...
