Test Overview
This test uses JUnit's @MethodSource to supply multiple sets of data to a factory method. It verifies that the factory method creates objects correctly for each input.
This test uses JUnit's @MethodSource to supply multiple sets of data to a factory method. It verifies that the factory method creates objects correctly for each input.
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; class Product { private final String name; private final int price; Product(String name, int price) { this.name = name; this.price = price; } String getName() { return name; } int getPrice() { return price; } } public class ProductFactoryTest { static Stream<Product> productProvider() { return Stream.of( new Product("Book", 10), new Product("Pen", 2), new Product("Notebook", 5) ); } @ParameterizedTest @MethodSource("productProvider") void testProductCreation(Product product) { assertNotNull(product); assertNotNull(product.getName()); assertTrue(product.getPrice() > 0); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes ProductFactoryTest class | - | PASS |
| 2 | JUnit calls productProvider() method to get test data stream | Stream of 3 Product objects is created | - | PASS |
| 3 | JUnit runs testProductCreation() with first Product("Book", 10) | Product object with name 'Book' and price 10 is passed to test | assertNotNull(product), assertNotNull(product.getName()), assertTrue(product.getPrice() > 0) | PASS |
| 4 | JUnit runs testProductCreation() with second Product("Pen", 2) | Product object with name 'Pen' and price 2 is passed to test | assertNotNull(product), assertNotNull(product.getName()), assertTrue(product.getPrice() > 0) | PASS |
| 5 | JUnit runs testProductCreation() with third Product("Notebook", 5) | Product object with name 'Notebook' and price 5 is passed to test | assertNotNull(product), assertNotNull(product.getName()), assertTrue(product.getPrice() > 0) | PASS |
| 6 | All parameterized tests complete | All 3 Product objects tested successfully | - | PASS |