3

I have read that when using @Mock, it should be used with @RunWith(MockitoJUnitRunner.class), while for @MockBean, it uses with @RunWith(SpringRunner.class).

However, for @Mock, I see that both MockitoJunitRunner or SpringRunner can be used interchangeably. I am rather confused as to why SpringRunner is also working in this situation ?

@RunWith(MockitoJUnitRunner.class) // also work when @RunWith(SpringRunner.class) is used
public class testService {
  @InjectMocks
  private ServiceA serviceA;

  @Mock
  private DependencyA dependencyA;
}
once
  • 536
  • 7
  • 21

2 Answers2

3

to quote this thread when talking about @MockBean

the class is included in the spring-boot-test library. It allows to add Mockito mocks in a Spring ApplicationContext.

Basically @MockBean is the combination of an @Mock and a @InjectMocks. Therefore, you could also use @Mock with springrunner but ofcourse it is not recommended because it is more heavy weight.

Generally you would use Mockito for lightweight unit tests, whereas using @MockBean when you want a mocked servlet environment like in a component test or a hybrid integration test.

Difference between @Mock, @MockBean and Mockito.mock()

Daniel Jacob
  • 1,455
  • 9
  • 17
-1

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.

If your bean Injection happening via Autowired annotation, then @mock will not work.

Raushan Kumar
  • 1,195
  • 12
  • 21