Spring Boot provides a great way to write tests for your application. In this article, we'll take a look at how to use Mockito to test your Spring Boot application.
Mockito is a powerful mocking framework for Java. It is very popular in the Spring community. Mockito allows us to write tests that are isolated from the external world. This is very important when we want to test our business logic without relying on external services.
First, we need to add the Mockito dependency to our pom.xml
:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.0.0-beta.19</version>
<scope>test</scope>
</dependency>
We can now create a MockitoJUnitRunner
to run our tests:
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
}
Mockito is very easy to use with Spring Boot. We can simply annotate our test class with @MockBean
to create a mock of a Spring Bean:
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@MockBean
private MyService myService;
}
We can then use Mockito to stub the methods of MyService
:
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@MockBean
private MyService myService;
@Test
public void testMyService() {
// given
given(myService.doSomething()).willReturn("Hello world!");
// when
String result = myService.doSomething();
// then
assertThat(result).isEqualTo("Hello world!");
}
}
In this article, we've seen how to use Mockito to test a Spring Boot application. Mockito is a very powerful tool that can help us write better tests.