When running tests, it is sometimes necessary to mock certain components within your application context. For example, you may have a facade over some remote service that is unavailable during development. Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment. Let's see the following test class where I have used Mocking:
package com.dineshonjava.accountservice; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import com.dineshonjava.accountservice.domain.Account; import com.dineshonjava.accountservice.service.AccountService; @RunWith(SpringRunner.class) @SpringBootTest public class AccountControllerTest { @MockBean AccountService accountService; @Test public void findAllByCustomerId() { assertFalse(accountService.findAllByCustomerId(1000).size() ==
3); } @Test public void testAddAccount_returnsNewAccount(){ when(accountService.save(any(Account.class))).thenReturn(new
Account(200, 200.20, 1000, "SAVING", "SBIWO111", "SBIW")); assertThat(accountService.save(new Account(200, 200.20, 1000,
"SAVING", "SBIWO111", "SBIW")), is(notNullValue())); } @Test public void findAccountByAccountId() { assertTrue(accountService.findAccountByAccountId(200).getBalance().intValue() == 200); } }
Spring Boot includes a @MockBean annotation that can be used to define a Mockito mock for a bean inside your ApplicationContext. You can use the annotation to add new beans or replace a single existing bean definition. The annotation can be used directly on test classes, on fields within your test, or on @Configuration classes and fields. When used on a field, the instance of the created mock is also injected. Mock beans are automatically reset after each test method.