0
0
JUnittesting~3 mins

Why @MethodSource for factory methods in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one method to power hundreds of tests without repeating yourself?

The Scenario

Imagine you have many test cases that need different sets of data. You write each test by hand, copying and pasting data over and over. It feels like filling out the same form again and again without any help.

The Problem

Manually writing each test with repeated data is slow and boring. It's easy to make mistakes like typos or forgetting to update one test. When data changes, you must fix every test separately, which wastes time and causes errors.

The Solution

@MethodSource lets you create one method that makes all the test data for you. Your tests just ask for the data from this method. This means less copying, fewer mistakes, and easy updates in one place.

Before vs After
Before
void test1() { assertEquals(2, add(1,1)); }
void test2() { assertEquals(3, add(1,2)); }
After
@ParameterizedTest
@MethodSource("dataProvider")
void testAdd(int a, int b, int expected) { assertEquals(expected, add(a,b)); }
static Stream<Arguments> dataProvider() { return Stream.of(Arguments.of(1,1,2), Arguments.of(1,2,3)); }
What It Enables

You can run many tests easily with different data sets, all managed cleanly in one place.

Real Life Example

Testing a calculator app with many input pairs and expected results, without writing separate tests for each pair.

Key Takeaways

Manual test data copying is slow and error-prone.

@MethodSource centralizes test data creation.

Tests become cleaner, easier to maintain, and scalable.