Spring Boot Mockito Support: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 7: Line 7:


=Overview=
=Overview=
Spring Boot has built-in Mockito support and no additional dependencies are required in the Gradle <code>build.gradle</code> 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]]
[[@MockBean]]


Mocks will be automatically reset across tests.
Mocks will be automatically reset across tests.
=Dependencies=
=Dependencies=
<syntaxhighlight lang='groovy'>
<syntaxhighlight lang='groovy'>

Revision as of 02:04, 3 October 2021

External

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

Mocks will be automatically reset across tests.

Dependencies

dependencies {
  ...
  testImplementation 'org.springframework.boot:spring-boot-starter-test'
  testImplementation 'org.mockito:mockito-core:3.12.4'
}

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");
    }
}