spring - 如何使用 Mockito 测试 Spring Boot 中的 Java 注解 Hibernate 配置类?

标签 spring unit-testing spring-boot mocking mockito

我正在使用 Mysql DB 开发 SPringBoot+Hibernate+REST 项目。我想知道如何对下面的类(class)进行单元测试。有人告诉我,模拟是最好的方法。我认为这与数据库模拟测试有关。即使在网上研究了很多之后我也没有任何线索。有人可以指导我应该如何测试它吗?如果我的项目中有使用这些数据库连接的 DAO 类,我还需要测试下面的类吗?我什至有需要测试的 RestController 类。请指导我应该如何继续这件事。我是初学者。

DBConfiguration.Java

package com.youtube.project.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

@PropertySource(value = { "classpath:application.properties" })
@Configuration
@EnableTransactionManagement
public class DBConfiguration {

    @Value("${jdbc.driverClassName}")
    private String driverClass;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${hibernate.dialect}")
    private String dialect;

    @Bean
    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(url,username,password);
        dataSource.setDriverClassName(driverClass);
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
        factory.setDataSource(getDataSource());
        factory.setHibernateProperties(hibernateProperties());
        factory.setPackagesToScan(new String[] {"com.youtube.project"});
        return factory;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", dialect);
        properties.put("hibernate.hbm2ddl.auto", "update");
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory factory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(factory);
        return transactionManager;
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
          LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
          em.setDataSource(getDataSource());
          em.setPackagesToScan(new String[] { "com.youtube.project.model" });     
          JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
          em.setJpaVendorAdapter(vendorAdapter);
          return em;
       }
} 

最佳答案

I want to know how I can Unit Test the below class

嗯,这有点复杂,因为您的配置类实际上会连接到数据库,因此这个类本身对于“单元测试”来说实际上并不是非常理想。

因为单元测试是软件测试的一个级别,其中测试各个单元/组件(单元是应用程序中最小的可测试部分)。它通常有一个或几个输入,通常有一个输出。

恕我直言,我会将其作为集成测试,因为您需要连接到数据库。

如何进行测试:

TL;DR - 不必为此类编写显式测试。

通过在主类上运行@SpringBootTest,您的类应该作为副作用进行测试。

说明:

显式测试此类没有什么意义,因为您基本上将测试:

  • bean 是否已创建
  • @Value 字段是否填充了值
  • 是否已建立与数据库的连接

从这三件事中,只有第三点是有效的测试,前两点是 Spring 开发人员在编写框架时测试的。话虽这么说,连接到数据库更多的是集成测试而不是单元测试。如果您想对此进行测试,可以使用内存数据库,例如 H2,它可以配置为仅在测试时运行。

I have DAO classes in my project which use thse db connections, do I still need to test the below Class? I even have RestController Class which needs to be tested.

Spring 对测试应用程序切片(应用程序的一部分,例如:一次一个类或一个类 + 它的依赖项)提供了强大的支持。

具体:

  • 对于 DAO 类,请查看 @DataJpaTestTestEntityManager 类。
  • 对于 Controller 类,请使用 @WebMvcTestMockMvc 类。

这些东西旨在让您使用 Spring Boot 进行测试更容易。一些基本信息,您可以查看this文章。

希望这有帮助

关于spring - 如何使用 Mockito 测试 Spring Boot 中的 Java 注解 Hibernate 配置类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55235903/

相关文章:

使用 thymeleaf 的 Java spring-boot 登录示例代码

java - 尝试提供图像时如何解决 Spring 中的 "No converter for [class [B] with preset Content-Type ' image/png'"错误?

java - spring boot war部署到tomcat给出404错误

reactjs - 为什么授权 header token 未显示在我的浏览器中

unit-testing - NUnit,TestDriven.Net : Duplicate test results with partial test classes

java - 如何通过一些用例测试 Apache Nutch 插件

java - 如何在 ConstraintValidator 中使用 @Autowired?

Spring boot - Application.properties 中的自定义变量

java - 使用 Mockito 模拟另一个类中的类方法

java - 如何在 CrudRepository 上使用 findAll() 返回 List 而不是 Iterable