Spring Boot Mockito Support: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 25: Line 25:
</syntaxhighlight>
</syntaxhighlight>
=Testing with <tt>@MockBean</tt>=
=Testing with <tt>@MockBean</tt>=
Annotate the test with <code>@SpringBootTest</code>. This will automatically allow injections of all real components from the application, '''including''' the JPA repositories. This is important, because a H2-based JPA repository is better than a mock.
<syntaxhighlight lang='java'>
@SpringBootTest
public class SomeControllerTest {
  //
  // this is the real controller to test
  //
  @Autowired
  private SomeController someController
  @Test
  public void test() {
      result = someController.someMethod(...);
      assertEquals(..., result.someStuff());
  }
}
</syntaxhighlight>


=Example=
=Example=

Revision as of 02:17, 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 inject 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, because it tests the real persistence logic.

@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
}

Testing with @MockBean

Annotate the test with @SpringBootTest. This will automatically allow injections of all real components from the application, including the JPA repositories. This is important, because a H2-based JPA repository is better than a mock.

@SpringBootTest
public class SomeControllerTest {

   //
   // this is the real controller to test
   // 
   @Autowired
   private SomeController someController

   @Test
   public void test() {
      result = someController.someMethod(...);
      assertEquals(..., result.someStuff());
   }
}

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