Deniss M. Deniss M. - 1 month ago 5x
Java Question

Test Spring-Boot Repository interface methods without touching the database using Mockito

I have the following test class:

@SpringApplicationConfiguration(classes = Application.class)
public class TransactionServiceTests {

public MockitoRule mockitoRule = MockitoJUnit.rule();

private MessagingService mockMessagingService;
private CustomerRepository mockCustomerRepository;

TransactionService transactionService;

public void testTransactionBetweenCustomersAndBalanceOfReceiver() {

int AMOUNT = 50;

// prepare your test data unless you always expect those values to exist.
Customer customerReceiver = new Customer();

Customer customerSender = new Customer();

int expectedReceiverAmount = customerReceiver.getBalance() + AMOUNT;
int expectedSenderAmount = customerSender.getBalance() - AMOUNT;
transactionService.makeTransactionFromSenderToReceiver(customerSender, customerReceiver, AMOUNT);

assertEquals(expectedSenderAmount, customerSender.getBalance());
assertEquals(expectedReceiverAmount, customerReceiver.getBalance());


This is the TransactionService. class itself:

public class TransactionService {

private MessagingService messagingService;
private CustomerRepository customerRepository;

private static final Logger log = LoggerFactory.getLogger(TransactionService.class);

public TransactionService(MessagingService messagingService, CustomerRepository customerRepository){
Assert.notNull(messagingService, "MessagingService cannot be null");
this.messagingService = messagingService;
Assert.notNull(customerRepository, "CustomerRepository cannot be null");
this.customerRepository = customerRepository;

public void makeTransactionFromSenderToReceiver(Customer sender, Customer receiver, int amount) {

if (sender.getBalance() >= amount) {
sender.setBalance(sender.getBalance() - amount);
receiver.setBalance(receiver.getBalance() + amount);;;

else {
throw new RuntimeException();

During the test, it is adding the above mentioned users to my live database and leaving them there even after the tests are finished. Can I in some way tell Mockito to not touch my database? Or is that totally not possible?


"Mock" your repository method calls. Also, use @InjectMocks instead @Autowired for TransactionService. And you can also use MockitoJUnitRunner. How to mock repository calls:


To verify that mocked method call has been invoked use:

verify(customerRepository, times(1)).save(sender);

Also, remember one thing: You are testing services! Therefore, all calls to database should be mocked.