Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SpringRunner with @Mock

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;
}
like image 907
once Avatar asked Jan 24 '26 16:01

once


1 Answers

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()

like image 123
Daniel Jacob Avatar answered Jan 27 '26 06:01

Daniel Jacob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!