saravanan
saravanan

Reputation: 171

What exactly is the purpose of SpringExtension?

What exactly SpringExtension do here? Even without that, the test case executes below as expected.

As per the doc doc

SpringExtension integrates the Spring TestContext Framework into JUnit 5's Jupiter programming model.

To use this extension, simply annotate a JUnit Jupiter based test class with @ExtendWith(SpringExtension.class), @SpringJUnitConfig, or @SpringJUnitWebConfig.

Unit Test with SpringExtension

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SellCarService.class)
class SellCarServiceTest {

    @Autowired
    private SellCarService carService;

    @Test
    public void testGetCarId() {
        String actual = carService.getCarDetails("1234");
        String expected = "PRIUS";
        Assertions.assertEquals(expected, actual);
    }
}

Simple Unit Test

class SellCarServiceTest {

    private final SellCarService carService = new SellCarService();

    @Test
    public void testGetCarId() {
        String actual = carService.getCarDetails("1234");
        String expected = "PRIUS";
        Assertions.assertEquals(expected, actual);
    }
}

If we want to use @Autowired in test classes, then we can go for the first approach or else we can use the simple approach as mentioned later. Is this understanding correct?

Or what is the advantage we get if we use SpringExtension or MockitoExtension?

Upvotes: 0

Views: 3292

Answers (1)

Johan Nordlinder
Johan Nordlinder

Reputation: 1886

You get no advantage of using the SpringExtension in this test class as you are not using any Mockito mocks.

You add @ExtendWith(SpringExtension.class) to the test class when you want to use the Mockito annotations such as @Mock, @Mockbean etc.

You are correct regarding @Autowired, there are also other ways to make autowiring work such as using the @SpringBootTest annotation.

Upvotes: -1

Related Questions