Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between @RunWith(MockitoJUnitRunner.class) and @RunWith(SpringJUnit4ClassRunner.class)? When to use it appropriately?

What's the difference between @RunWith(MockitoJUnitRunner.class) and @RunWith(SpringJUnit4ClassRunner.class)? When to use it appropriately?

like image 453
Pooja Avatar asked Aug 31 '25 23:08

Pooja


1 Answers

MockitoJUnitRunner

  • specific for use with the Mockito test framework
  • the Mockito framework helps with mocking dependencies when you want to focus your tests on a single class and avoid invoking methods on dependencies (instead invokes a mock/dummy that is easily configured).
  • Above is what mockito is used for, but for more on this runner specifically - from the docs: "keeps tests clean and improves debugging experience". "Runner is completely optional - there are other ways you can get @Mock working". Source - https://static.javadoc.io/org.mockito/mockito-core/2.6.8/org/mockito/junit/MockitoJUnitRunner.html

SpringJunit4ClassRunner

  • specific for use with the spring framework
  • used for integration tests when it is required to load the spring context (create spring beans, perform dependency injection, etc).
  • In integration tests you may not do as much mocking of dependencies but you can do both in the same test.
  • Integration tests are useful when you would like to test loading the spring context or perhaps test from the service/high level all the way down to lower levels like data access with a single test.

In some cases you may want to use both - like an integration test where you would also like to mock some dependencies (perhaps they make remote calls). Unfortunately you can't use two @RunWiths but this is a good post about that - Multiple RunWith Statements in jUnit

like image 166
camtastic Avatar answered Sep 03 '25 12:09

camtastic