简体   繁体   English

如何使用Spock测试LocalContainerEntityManagerFactoryBean

[英]How to test LocalContainerEntityManagerFactoryBean using Spock

How can I test my db connection using spock? 如何使用spock测试我的数据库连接? I know how to do this using JUnit and the test pass, but when I am trying do similar thing using Spock I am getting NullPointerException and Cannot invoke method getDataSource() on null object. 我知道如何使用JUnit和测试传递来做到这一点,但是当我尝试使用Spock做类似的事情时,我得到NullPointerException并且无法在null对象上调用方法getDataSource()

@SpringBootTest
@ContextConfiguration(classes = DatabaseConfig.class)
@WebAppConfiguration
class DatabaseConfigTest extends Specification {

    @Autowired
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean;

    def "Should connect to database."() {
        when:
        entityManagerFactoryBean.getDataSource().getConnection()
        then:
        notThrown(SQLException.class)
    }
}

How to test the DB connection using Spock, my class that is responsible for database configuration is DatabaseConfig.class 如何使用Spock测试数据库连接,我的负责数据库配置的类是DatabaseConfig.class

This should give you what you are looking for. 这应该可以满足您的需求。 Remove the ContextConfiguration and WebAppConiguration annotations. 删除ContextConfiguration和WebAppConiguration注释。 Inject DataSource directly. 直接注入DataSource。

@SpringBootTest
class DatabaseConfigTest extends Specification {

    @Autowired
    DataSource dataSource;

    def "Should connect to database."() {
        when:
        dataSource.getConnection()
        then:
        notThrown(SQLException.class)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM