当前位置: 首页 > 知识库问答 >
问题:

如何用服务和存储库为spring数据设置单元测试?

鲁德佑
2023-03-14
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class DealServiceTest {

    @Configuration
    static class ContextConfiguration {

        // this bean will be injected into the OrderServiceTest class
        @Bean
        public DealService orderService() {
            DealService dealService = new DealService();
            // set properties, etc.
            return dealService;
        }

        @Bean
        public EmployeeService employeeService(){
            EmployeeService employeeService = new EmployeeService();
            return employeeService;
        }

    }

    @Autowired
    DealService dealService;

    @Autowired
    EmployeeService employeeService;

    @Test
    public void createDeal() throws ServiceException {
        Employee employee = new Employee("Daniel", "tuttle", "danielptm@me.com", "dannyboy", "secret password", 23.234, 23.23);
        Deal d = dealService.createDeal("ADSF/ADSF/cat.jpg", "A title goes here", "A deal description", 23.22, "Name of business", 23.23,23.23, employee, "USA" );
        Assert.assertNotNull(d);

    }

}

然后我有我的服务课,看起来像这样

@Service
public class DealService {

    @Autowired
    private DealRepository dealRepository;

    public Deal createDeal(String image, String title, String description, double distance, String location, double targetLat, double targetLong, Employee employee, String country) throws ServiceException {
        Deal deal = new Deal(image, title, description, distance, location, targetLat, targetLong, employee, country);
        try {
            return dealRepository.save(deal);
        }catch(Exception e){
            throw new ServiceException("Could not create a deal: "+deal.toString(), e);
        }
    }

    public Deal updateDeal(Deal d) throws ServiceException {
        try{
            return dealRepository.save(d);
        }catch(Exception e){
            throw new ServiceException("Could not update deal at this time: "+d.toString(),e);
        }
    }

    public List<Deal> getAllDealsForEmployeeId(Employee employee) throws ServiceException {
        try{
            return dealRepository.getAllDealsBy_employeeId(employee.getId());
        }catch(Exception e){
            throw new ServiceException("Could not get deals for employee: "+employee.getId(), e);
        }
    }

}

然后是我的存储库:

public interface DealRepository extends CrudRepository<Deal, Long>{

    public List<Deal> getDealsBy_country(String country);

    public List<Deal> getAllDealsBy_employeeId(Long id);

}
@Configuration
@EnableJpaRepositories("com.globati.repository")
@EnableTransactionManagement
public class InfrastructureConfig {

    @Bean
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("com.mysql.jdbc.Driver");
        config.setJdbcUrl("jdbc:mysql://localhost:3306/DatabaseProject");
        config.setUsername("awesome");
        config.setPassword("database");
        return new HikariDataSource(config);
    }

//  @Bean
//  public DataSource derbyDataSource(){
//      HikariConfig config = new HikariConfig();
//      config.setDriverClassName("jdbc:derby:memory:dataSource");
//      config.setJdbcUrl("jdbc:derby://localhost:1527/myDB;create=true");
//      config.setUsername("awesome");
//      config.setPassword("database");
//
//      return new HikariDataSource(config);
//
//  }

    @Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory factory) {
        return new JpaTransactionManager(factory);
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {

        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setDatabase(Database.MYSQL);
        adapter.setGenerateDdl(true);

        return adapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dataSource()); //Get data source config here!
        factory.setJpaVendorAdapter(jpaVendorAdapter());
        factory.setPackagesToScan("com.globati.model");

        return factory;
    }
}

共有1个答案

高祺
2023-03-14

对于要注入的存储库bean,

>

  • 您需要使用spring-data注释之一来启用存储库。因此,将@enable*repositories添加到您的配置类中

    您还需要配置dB工厂和其他相关bean。我正在使用Mongo,并且配置了mongoDbFactory bean

    @Configuration
    @WebAppConfiguration
    @ComponentScan(basePackages = "com.amanu.csa",
            excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = WebConfig.class))
    @EnableMongoRepositories(repositoryImplementationPostfix = "CustomImpl")
    class TestConfig {
    
        @Bean
        Mongo mongo() throws Exception {
            return new MongoClient("localhost")
        }
    
        @Bean
        MongoDbFactory mongoDbFactory() throws Exception {
            return new SimpleMongoDbFactory(mongo(), "csa_test")
        }
    
        @Bean
        MongoTemplate mongoTemplate() throws Exception {
            MongoTemplate template = new MongoTemplate(mongoDbFactory())
            template.setWriteResultChecking(WriteResultChecking.EXCEPTION)
            return template
        }
    }
    
    @ContextConfiguration(classes = TestConfig)
    @RunWith(SpringRunner.class)
    class OrganizationServiceTest {
    
        @Autowired
        OrganizationService organizationService
    
         @Test
        void testRegister() {
            def org = new Organization()
            //...
            organizationService.register(org)
            // ...
        }
    

  •  类似资料:
    • 又不想工作,我不知道是怎么回事。 日志包含以下消息: 将项目放在github https://github.com/romanych2021/testjpaspring上

    • 我正在尝试对服务方法进行单元测试。服务方法调用spring数据存储库方法来获取一些数据。我想模拟这个存储库调用,并自己提供数据。如何做到这一点?在Spring Boot文档之后,当我模拟存储库并在测试代码中直接调用存储库方法时,模拟工作正常。但是,当我调用服务方法时,反过来调用存储库方法,mocking就不起作用了。下面是示例代码: 服务级别: 测试等级:

    • 我想要一个在Spring数据的帮助下创建的存储库(例如)。我不熟悉spring-data(但不熟悉spring),我使用本教程。我选择的处理数据库的技术是JPA2.1和Hibernate。问题是我不知道如何为这样的存储库编写单元测试。 让我们以方法为例。由于我正在进行测试--首先,我应该为它编写一个单元测试--这就是我遇到三个问题的地方: > 首先,如何将的模拟注入到不存在的接口实现中?Sprin

    • 在我的项目中,我在进行单元测试时遇到了问题。一个问题是,仅仅进行联调就可以更快地编写,并且还可以测试组件是否真正协同工作。单元测试新颖的“算法”之类的似乎要容易得多。单元测试服务类感觉是错误和无用的。 我使用mockito来模拟spring数据存储库(以及DB访问)。问题是,如果我告诉模拟存储库在方法调用getById时返回实体A,它显然会返回实体A,服务也会返回实体A。是的,该服务做了一些额外的

    • 问题内容: 在application-context.xml中定义mongo存储库时遇到问题 以下是我在xml中得到的错误 我附上env的屏幕截图,以供参考。我正在使用eclipse Kepler版本和pom属性文件是这样的 Spring Data Commons版本是1.7 Spring Data Mongo DB版本1.4。打开上下文xml时,我在eclipse项目中看到错误。 有趣的是,我还

    • 我有一个Spring Data JPA存储库,只要不添加Spring Security性依赖项(spring-boot-starter-security)并在存储库上添加相应的方法授权注释,单元测试就可以正常工作。添加后,在运行单元测试时,我会得到一个AuthenticationCredentialsNotFound异常。 如何在单元测试中“验证”对存储库方法的调用?