0
0
JUnittesting~10 mins

@MethodSource for factory methods in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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);
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes ProductFactoryTest class-PASS
2JUnit calls productProvider() method to get test data streamStream of 3 Product objects is created-PASS
3JUnit runs testProductCreation() with first Product("Book", 10)Product object with name 'Book' and price 10 is passed to testassertNotNull(product), assertNotNull(product.getName()), assertTrue(product.getPrice() > 0)PASS
4JUnit runs testProductCreation() with second Product("Pen", 2)Product object with name 'Pen' and price 2 is passed to testassertNotNull(product), assertNotNull(product.getName()), assertTrue(product.getPrice() > 0)PASS
5JUnit runs testProductCreation() with third Product("Notebook", 5)Product object with name 'Notebook' and price 5 is passed to testassertNotNull(product), assertNotNull(product.getName()), assertTrue(product.getPrice() > 0)PASS
6All parameterized tests completeAll 3 Product objects tested successfully-PASS
Failure Scenario
Failing Condition: productProvider() returns a Product with null name or price <= 0
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @MethodSource annotation do in this test?
ARuns the test only once
BSupplies multiple Product objects as test inputs
CCreates a mock Product object
DSkips the test if no data is found
Key Result
Using @MethodSource with factory methods allows running the same test logic with different inputs, improving test coverage and reducing code duplication.