Spring Boot Mockito Support: Difference between revisions
Jump to navigation
Jump to search
Line 16: | Line 16: | ||
Note that mocks will be automatically reset across tests. | Note that mocks will be automatically reset across tests. | ||
=Dependencies= | ==Dependencies== | ||
<syntaxhighlight lang='groovy'> | <syntaxhighlight lang='groovy'> | ||
dependencies { | dependencies { |
Revision as of 02:08, 3 October 2021
External
- https://www.baeldung.com/injecting-mocks-in-spring
- https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4#mocking-and-spying
Internal
Overview
Spring Boot has built-in Mockito support and no additional dependencies are required in the Gradle build.gradle
file to use Mockito mocks. This article describes the minimal amount of steps to use Mockito mocks in tests, alongside whatever components and real JPA repositories the application uses. Note that a H2-based JPA repository is better than a Mockito mock.
@MockBean
The org.springframework.boot.test.mock.mockito.MockBean
annotation injects Mockito mocks built around whatever component is specified in the test. Using @MockBean is the key to easily using mocks from Spring Boot unit tests.
Note that mocks will be automatically reset across tests.
Dependencies
dependencies {
...
testImplementation 'org.springframework.boot:spring-boot-starter-test' // no special Mockito dependency is necessary
}
Example
@RunWith(SpringRunner.class)
@SpringBootTest
public class SomeTest {
@Autowired
private TestRestTemplate restTemplate;
@MockBean
private SomeService someService;
@Before
public void setup() {
// this stubs behavior
given(someService.getSomething("blah")).willReturn(new Something("blah"));
}
@Test
public void test() {
restTemplate.getForEntity("/{username}/something, String.class, "blue");
}
}