@RunWith(SpringRunner.class) vs @RunWith(MockitoJUnitRunner.class)

JunitMockitoSpring Test

Junit Problem Overview


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(SpringRunner.class) . Does using @RunWith(SpringRunner.class) has any advantages over using @RunWith(MockitoJUnitRunner.class)? Can i still use feature like @Injectmock, @Mock, @Spy with @RunWith(SpringRunner.class)

Junit Solutions


Solution 1 - Junit

The SpringRunner provides support for loading a Spring ApplicationContext and having beans @Autowired into your test instance. It actually does a whole lot more than that (covered in the Spring Reference Manual), but that's the basic idea.

Whereas, the MockitoJUnitRunner provides support for creating mocks and spies with Mockito.

However, with JUnit 4, you can only use one Runner at a time.

Thus, if you want to use support from Spring and Mockito simultaneously, you can only pick one of those runners.

But you're in luck since both Spring and Mockito provide rules in addition to runners.

For example, you can use the Spring runner with the Mockito rule as follows.

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {

	@Rule
	public MockitoRule rule = MockitoJUnit.rule();

	@Mock
	MyService myService;

	// ...
}

Though, typically, if you're using Spring Boot and need to mock a bean from the Spring ApplicationContext you would then use Spring Boot's @MockBean support instead of simply @Mock.

Solution 2 - Junit

When SpringRunner.class is used, Spring provides corresponding annotations:

  • @MockBean
  • @SpyBean

Mocks are injected to objects under tests via @Autowired annotation. To enable this functionality tests must be annotated with

  • @SpringBootTest

or

  • @TestExecutionListeners(MockitoTestExecutionListener.class)

More details and examples can be found in the official documentation: Mocking and Spying Beans

Solution 3 - Junit

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 Spring TestContext Framework with a runner other than this one, use org.springframework.test.context.junit4.rules.SpringClassRule and org.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.

Solution 4 - Junit

Scenario 2019 November : spring-boot : 2.1.1.RELEASE

  • You have a spring boot api rest
  • You need to test a service called MySuperSpringService
  • But, inside MySuperSpringService, are required two more autowires. One to perform a sql select (MyJpaRepository) and another to call an external api rest (MyExternalApiRest)
@Service
public class MySuperSpringService {

  @Autowired
  private MyRepository innerComponent1;

  @Autowired
  private MyExternalApiRest innerComponent2;

  public SomeResponse doSomething(){}
}

How test MySuperSpringService mocking database and external api rest ?

So, in order to test this service MySuperSpringService which needs another spring beans: MyJpaRepository and MyExternalApiRest, you need to mock them using @MockBean and create the result as you need.

import static org.mockito.Mockito.when;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

import junit.framework.TestCase;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = your.package.Application.class)
public class MySuperSpringServiceTest extends TestCase {

  @Autowired
  private MySuperSpringService serviceToTest;

  @MockBean
  private MyRepository myRepository;

  @MockBean
  private MyExternalApiRest myExternalApiRest;

  @Before
  public void setUp()  {

    Object myRepositoryResult = new Object();
    //populate myRepositoryResult as you need
    when(myRepository.findByClientId("test.apps.googleusercontent.com"))
        .thenReturn(myRepositoryResult);

    Object myExternalApiRestResult = new Object();
    //populate myExternalApiRestResult as you need
    when(myExternalApiRest.listUserRoles("[email protected]")).thenReturn(myExternalApiRestResult);

  }

  @Test
  public void testGenerateTokenByGrantTypeNoDatabaseNoGoogleNoSecurityV1(){
    SomeResponse response = serviceToTest.doSomething();
    //put your asserts here
  }

}

Solution 5 - Junit

you can absolutely use SpringRunner for both unit tests and integration tests. SpringRunner Tutorial

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser8710021View Question on Stackoverflow
Solution 1 - JunitSam BrannenView Answer on Stackoverflow
Solution 2 - JunitVaLView Answer on Stackoverflow
Solution 3 - JunitWesternGunView Answer on Stackoverflow
Solution 4 - JunitJRichardszView Answer on Stackoverflow
Solution 5 - JunitCaffeine CoderView Answer on Stackoverflow