How to define a Mock Repository in Spring Boot

The key to define a Mock Repository is the @Repository annotation. @Repository is a Spring annotation that indicates that the decorated class is a repository.

A Repository is a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects. It is a specialization of the @Component annotation allowing for implementation classes to be autodetected through classpath scanning.

spring boot mock in memory repository

Let’s start from a simple interface:

package com.sample;

import java.util.List;

public interface CustomerRepository {
  List<Customer> findAll();

  Customer findCustomer(Long id);
}

Now we will define an implementation of this interface that is tagged with @Repository:

package com.sample;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

@Repository
public class MockCustomerRepository implements CustomerRepository {
  private final List<Customer> customers = new ArrayList<>();

  public MockCustomerRepository() {
    this.customers.add(new Customer(1L, "John", "Smith"));
    this.customers.add(new Customer(2L, "Mark", "Spencer"));
    this.customers.add(new Customer(3L, "Andy", "Doyle"));
  }

  @Override
  public List<Customer> findAll() {
    return this.customers;
  }

  @Override
  public Customer findCustomer(Long id) {
    for (Customer customer : this.customers) {
      if (ObjectUtils.nullSafeEquals(customer.getId(), id)) {
        return customer;
      }
    }
    return null;
  }
}

Here is how to use the Mock Repository in a Spring Boot application:

package sample.hateoas;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.sample.Customer;
import com.sample.MockCustomerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SpringBootApplication public class DemoApplication {
  private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
  @Bean public CommandLineRunner demo(MockCustomerRepository repository) {
    return (args) -> {
      log.info("Customers found with findAll():");log.info("-------------------------------");
      for (Customer person: repository.findAll()) {
        log.info(person.toString());
      }
      log.info("");
      // fetch an individual customer by ID
      log.info("Customer 1 " + repository.findOne(1 L).getLastName());
    };
  }
}