What if you could write one method to power hundreds of tests without repeating yourself?
Why @MethodSource for factory methods in JUnit? - Purpose & Use Cases
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.
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.
@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.
void test1() { assertEquals(2, add(1,1)); }
void test2() { assertEquals(3, add(1,2)); }@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)); }
You can run many tests easily with different data sets, all managed cleanly in one place.
Testing a calculator app with many input pairs and expected results, without writing separate tests for each pair.
Manual test data copying is slow and error-prone.
@MethodSource centralizes test data creation.
Tests become cleaner, easier to maintain, and scalable.