I was using @RunWith(MockitoJUnitRunner.class)
for my junit test with mockito. But now i am working with spring boot app and trying to use @RunWith(Spring
As per the JavaDoc:
SpringRunner is an alias for the
SpringJUnit4ClassRunner
. To use this class, simply annotate a JUnit 4 based test class with@RunWith(SpringRunner.class)
. If you would like to use the SpringTestContext
Framework with a runner other than this one, useorg.springframework.test.context.junit4.rules.SpringClassRule
andorg.springframework.test.context.junit4.rules.SpringMethodRule
.
And the JavaDoc of TestContext
:
TestContext
encapsulates the context in which a test is executed, agnostic of the actual testing framework in use.
That of method getApplicationContext()
:
Get the application context for this test context, possibly cached. Implementations of this method are responsible for loading the application context if the corresponding context has not already been loaded, potentially caching the context as well.
So, SpringRunner does load the context and is responsible for maintaining it. For example, if you want to persist data into an embedded database, like H2 in-memory database, you have to use SpringRunner.class
; and, to clean the tables to get rid of the records you inserted after every test, you annotate the test with @DirtiesContext
to tell Spring to clean it.
But, this is already an integration or component test. If your test is pure unit test, you don't have to load DB, or you just want to verify some method of a dependency is called, MockitoJUnit4Runner
suffices. You just use @Mock
as you like and Mockito.verify(...)
and the test will pass. And it is a lot quicker.
Test should be fast. As fast as possible. So whenever possible, use MockitoJUnit4Runner
to speed it up.