如何在 Spring Boot 中模拟存储库Mock Repository

x33g5p2x  于2022-09-29 转载在 Spring  
字(2.1k)|赞(0)|评价(0)|浏览(676)

定义模拟存储库的关键是 @Repository 注释。 @Repository 是一个 Spring 注解,表示被修饰的类是一个存储库。

存储库是一种封装存储、检索和搜索行为的机制,它模拟对象集合。 它是 @Component 注释的特化,允许通过类路径扫描自动检测实现类。

让我们从一个简单的界面开始:

package com.sample;

import java.util.List;

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

  Customer findCustomer(Long id);
}

现在我们将定义一个使用@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;
  }
}

以下是在 Spring Boot 应用程序中使用 Mock Repository 的方法:

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

相关文章

微信公众号

最新文章

更多