- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在为我的应用程序编写几个单元测试,使用 DBUnit (2.5.3) 和 hibernate (5.1.0)。在编写这些测试的过程中,我遇到了一些奇怪的行为。
@Test
public void test() {
Channel channel = new Channel();
channel.setName("My Channel");
channel.setId(14L);
channel = channelRepository.save(channel);
Channel found = channelRepository.findOne(14L);
Assert.assertNotNull(found);
List<Channel> channels = channelRepository.findAll();
Assert.assertEquals(1, channels.size());
}
运行上面的测试,你会期望这个测试成功。但是,此测试在代码的最后一行失败,打印出我的对象“channels”是一个空列表。奇怪的是,“findOne”确实找到了我保存的实体,而 findAll 根本找不到任何实体。我怀疑某种缓存问题,但我似乎无法找到解决方法。
这里是一些在设置过程中使用的类
测试类本身:
public class ChannelRepositoryTest extends AbstractRepositoryTest {
@Autowired
private ChannelRepository channelRepository;
@Override
protected IDataSet getDataSet() throws Exception {
return null;
}
@Test
public void test() {
Channel channel = new Channel();
channel.setName("My Channel");
channel.setId(14L);
channel = channelRepository.save(channel);
Channel found = channelRepository.findOne(14L);
Assert.assertNotNull(found);
List<Channel> channels = channelRepository.findAll();
Assert.assertEquals(1, channels.size());
}
}
抽象存储库测试:
public abstract class AbstractRepositoryTest extends AbstractRTVTest {
private static final ByteArrayResource QUERY = new ByteArrayResource("SET REFERENTIAL_INTEGRITY FALSE".toString().getBytes(Charset.forName("UTF-8")));
@Autowired
private DataSource dataSource;
@Before
public void beforeEveryTest() throws Exception {
IDatabaseConnection dbConn = new DatabaseDataSourceConnection(dataSource);
ScriptUtils.executeSqlScript(dbConn.getConnection(), QUERY); // here to satisfy jenkins, otherwise we get constraint violation errors
dbConn.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,new H2DataTypeFactory());
if (getDataSet() != null) {
DatabaseOperation.CLEAN_INSERT.execute(dbConn, getDataSet());
}
}
protected abstract IDataSet getDataSet() throws Exception;
protected FlatXmlDataSetBuilder getFlatXmlDataSetBuilder() {
return new FlatXmlDataSetBuilder().setColumnSensing(true);
}
}
AbstractRTVTest:
@ContextConfiguration(classes = {HibernateTestConfiguration.class})
public abstract class AbstractRTVTest extends AbstractTransactionalJUnit4SpringContextTests {
}
HibernateTestConfiguration
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application-test.properties")
@ComponentScan(basePackages = {"be.persgroep.rtv"})
public class HibernateTestConfiguration {
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "be.persgroep.rtv.domain.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean(name = "mySimpleDataSource")
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:something;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.put("hibernate.hbm2ddl.auto", "create-drop");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.cache.use_second_level_cache", "false");
properties.put("hibernate.cache.use_query_cache", "false");
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
channel 库
public interface ChannelRepository extends JpaRepository<Channel, Long> {
}
Channel 只是一个简单的@Entity 注释类
@Entity
@Table(name = "ZENDERS", catalog = "")
public class Channel {
private long id;
private String name;
@Id
@Column(name = "ID")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "NAAM")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
application-test.properties
environment=local
server.port=8080
securityservice.baseUrl=
securityservice.apiKey=
spring.profiles.active=test
dpp.sec.springuser.application=RTV
# set to false to use profiles (default is actions) as granted authorities
dpp.sec.springuser.rolesAreActions=true
# set to true to allow access to authenticated users without granted authorities
dpp.sec.springuser.allowAuthenticationWithoutRoles=false
# comma seperated list of external providers: set to LDAP or LDS to only allow users from that provider
dpp.sec.springuser.externalProviderNames=LDAP,LDS
# prefix to prepend to all granted authorities (used by RoleVoter to distinguish from other security attributes)
dpp.sec.springuser.rolePrefix=AUTH_
#encrypt passwords with RSA for authentication
dpp.sec.springuser.useRsa=true
最后是 build.gradle 文件:
buildscript {
repositories {
maven { url "https://plugins.gradle.org/m2/" }
maven { url "https://artifactory.persgroep.cloud/artifactory/libs-release" }
}
dependencies {
classpath "net.persgroep.gradle:persgroep-gradle-plugins:1.3.3"
classpath 'gradle.plugin.com.gorylenko.gradle-git-properties:gradle-git-properties:1.4.17'
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
classpath "com.moowork.gradle:gradle-node-plugin:1.1.1"
classpath 'org.ajoberstar:gradle-git:1.7.2'
// classpath "com.github.iboyko.gradle.plugins:jpamodelgen-plugin:1.0.1" ?
}
ext["thymeleaf.version"] = "3.0.3.RELEASE"
ext["thymeleaf-layout-dialect.version"] = "2.1.2"
ext['hibernate.version'] = '5.1.0.Final'
}
allprojects {
repositories {
mavenCentral()
maven { url "https://artifactory.persgroep.cloud/artifactory/libs-release" }
}
apply plugin: 'net.persgroep.java'
apply plugin: 'net.persgroep.buildversion'
apply plugin: 'com.gorylenko.gradle-git-properties'
apply plugin: 'findbugs'
apply plugin: 'pmd'
apply plugin: 'jdepend'
apply plugin: 'org.ajoberstar.grgit'
findbugs {
reportsDir = file("$project.buildDir/findbugsReports")
effort = "max"
reportLevel = "high"
}
tasks.withType(FindBugs) {
reports {
xml.enabled = true
html.enabled = false
}
}
pmd {
ignoreFailures = true
}
tasks.withType(Pmd) {
reports {
xml.enabled = false
html.enabled = true
}
}
jdepend {
toolVersion = '2.9.1'
ignoreFailures = true
}
}
subprojects {
task listAllDependencies(type: DependencyReportTask) {}
apply plugin: 'net.persgroep.java'
apply plugin: 'net.persgroep.publish'
apply plugin: 'io.spring.dependency-management'
dependencies {
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement { imports { mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") } }
}
project('validation-tests'){
dependencies {
testCompile "info.cukes:cucumber-java:${cucumberVersion}"
testCompile "info.cukes:cucumber-junit:${cucumberVersion}"
testCompile "info.cukes:cucumber-picocontainer:${cucumberVersion}"
testCompile "org.seleniumhq.selenium:selenium-java:3.4.0"
testCompile "org.seleniumhq.selenium:selenium-support:3.4.0"
testCompile "io.github.bonigarcia:webdrivermanager:1.7.1"
testCompile group: 'org.seleniumhq.selenium', name: 'selenium-chrome-driver', version: '3.4.0'
}
// Don't run these tests by default
test.enabled = project.hasProperty("browser") && project.hasProperty("environment")
//test.enabled = false
test {
systemProperties = [
browser: project.findProperty('browser')?:'chrome',
baseTestUrl: "http://rtv." + (project.findProperty('environment') ?: 'test' )+ ".persgroep.net/"
]
}
}
project('domain:model'){
dependencies {
compile group: 'commons-lang', name: 'commons-lang', version: '2.6'
compile ('be.persgroep.adv:commons-adv-model:1.1.3'){
exclude module: 'orika-core'
}
compile group: 'ma.glasnost.orika', name: 'orika-core', version: '1.5.1'
compile("org.hibernate:hibernate-java8:5.1.0.Final")
compile group: 'com.fasterxml.jackson.core', name:'jackson-annotations'
compile group: 'com.fasterxml.jackson.datatype', name:'jackson-datatype-jsr310'
}
}
project('domain:services'){
dependencies {
compile project(':domain:model')
compile("org.springframework.boot:spring-boot-starter-security:${springBootVersion}")
compile("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}")
}
}
project('application'){
dependencies {
compile project(':domain:model')
compile project(':domain:services')
compile("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}")
}
}
project('infrastructure'){
apply plugin: 'com.moowork.node'
apply plugin: 'com.moowork.gulp'
apply plugin: 'org.springframework.boot'
apply plugin: 'net.persgroep.deploy'
apply plugin: 'net.persgroep.distzip'
apply plugin: 'war'
dependencies {
compile project(':application')
compile 'org.springframework.cloud:spring-cloud-starter-oauth2:1.2.0.RELEASE'
compile("org.springframework.boot:spring-boot-starter-web")
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
compile("org.springframework.boot:spring-boot-starter-batch")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-jdbc")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.2.RELEASE")
compile("org.thymeleaf.extras:thymeleaf-extras-java8time:3.0.0.RELEASE")
compile 'net.logstash.logback:logstash-logback-encoder:4.8'
compile "net.persgroep.utils.spring.boot:dpp-spring-boot-starter-jwt:${dppSecurity}"
compile group: 'be.persgroep.adv', name: 'commons-adv-io', version: '1.1.3'
compile group: 'com.oracle', name: 'ojdbc6', version: '11.2.0.3'
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.6'
compile 'org.webjars:bootstrap:3.3.7'
compile 'org.samba.jcifs:jcifs:1.3.17'
compile 'io.springfox:springfox-swagger2:2.7.0'
compile 'io.springfox:springfox-swagger-ui:2.7.0'
compile "net.persgroep.service.conversion:client:1.2"
compile "net.persgroep.diocontent.images.webservice:diocontent-webservice-client:4.0.13"
compile 'org.quartz-scheduler:quartz:2.2.1'
compile group: 'c3p0', name: 'c3p0', version: '0.9.0.4' // default c3p0 does not cut it and causes pipeline to fail
compile 'com.netflix.feign:feign-core:8.18.0'
compile 'com.netflix.feign:feign-jaxb:8.18.0'
compile 'com.netflix.feign:feign-gson:8.18.0'
compile 'com.googlecode.json-simple:json-simple:1.1.1'
compile group: 'org.json', name: 'json', version: '20170516'
compile "net.persgroep.utils.monitor:status:1.4"
compile "net.persgroep.utils.monitor:monitor:1.4"
compile("com.h2database:h2:1.4.195")
testCompile("org.dbunit:dbunit:2.5.3")
}
node {
version = '6.10.3'
npmVersion = '3.10.10'
download = true
nodeModulesDir = new File(projectDir, "src/main/client")
}
gulp {
// Set the directory where gulpfile.js should be found
workDir = new File(projectDir, "src/main/client")
// Whether colors should output on the terminal
colors = true
// Whether output from Gulp should be buffered - useful when running tasks in parallel
bufferOutput = false
}
springBoot {
buildInfo()
}
processResources() {
filesMatching('**/*.properties') {
expand(project.properties)
}
}
gulp_build.dependsOn 'installGulp'
// processes your package.json before running gulp build
gulp_build.dependsOn 'npmInstall'
// runs "gulp build" as part of your gradle build
war.dependsOn gulp_build
apply from: "$rootDir/deploy.gradle"
// needed to run the application on windows because of filename issues
task pathingJar(type: Jar) {
dependsOn configurations.runtime
appendix = 'pathing'
doFirst {
manifest {
// Build the Class-Path for absolute paths based on runtime dependencies.
attributes "Class-Path": configurations.runtime.files.collect {
it.toURL().toString().replaceFirst(/file:\/+/, '/')
}.join(' ')
}
}
}
bootRun {
dependsOn pathingJar
doFirst {
// Add the compiled app classed to the classpath of the pathing jar. Probably there is a gradle variable for them?
classpath = files("$buildDir/classes/main", "$buildDir/resources/main", "$projectDir/gsp-classes", pathingJar.archivePath)
}
}
}
task wrapper(type: Wrapper) {
gradleVersion = "${gradleWrapperVersion}"
}
tasks.withType(Test) {
reports.html.destination = file("${reporting.baseDir}/${name}")
}
build.gradle 中使用的几个属性位于 gradle.properties 中:
group=be.persgroep.rtv
cucumberVersion=1.2.5
gradleWrapperVersion=3.5
springBootVersion=1.5.3.RELEASE
dppSecurity=1.3.7
非常感谢任何帮助!
亲切的问候,
埃利亚斯
最佳答案
似乎有一个很微妙的逻辑错误。
应该是:
Assert.assertEquals(1, channels.size());
此外,请使用调试器检查channels
变量的值(例如,逐步调试):执行赋值后不应为空:channels = channelRepository.findAll();
.
使用了错误的事务管理器:使用了 JPA 存储库,因此,应该使用 JpaTransactionManager
而不是 HibernateTransactionManager
。因为默认情况下已经配置了正确的,所以删除 HibernateTransactionManager
bean 定义(transactionManager()
方法)就足够了。
希望这对您有所帮助。
关于java - Hibernate/DBunit 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45734718/
(新手 DBUnit 问题警报!) 看来每个表的 DBUnit 都会“从表中删除所有记录,然后执行插入操作”。 这意味着您无法使用 xml 加载文件顺序清除数据,因为在从其他表中删除记录之前,任何约束
我们正在使用 CsvDataFileLoader 加载我们的引用数据,如下所示: new InsertIdentityOperation(DatabaseOperation.CLEAN_INSERT)
您好,我正在尝试进行集成测试, 我使用码头作为容器和 dbunit 来填充内存数据库中的 HSQLDB。 我用来用 dataset.xml 文件填充数据库的代码是有效的,因为我在我的单元测试中使用了它
我有以下 java 代码,它给出了以下错误: import java.io.File; import java.io.FileOutputStream; import java.sql.Connect
我遇到了 DBUnit (V2.5.3) 的问题,我想将属性 FEATURE_ALLOW_EMPTY_FIELDS 设置为 true,但 DBUnit 忽略了此设置。我设置属性的代码是: Databa
我觉得这很容易理解,但是我很难找到有关如何更改DBUnit日志级别的信息。谁能为我解决这个问题? 最佳答案 避免了一段时间后,我找到了解决方案。 import org.slf4j.Logger imp
我更新了我的 composer.json 文件以包含 dbunit: "require-dev": { "phpunit/phpunit": "^7", "phpunit/dbunit
我正在使用 dBUnit 并试图用实际的 DB 数据集断言我预定义的 FlatXmlDataSet 的一行。问题是当数据来自 FlatXmlDataSet 时,我的验证码字段的 getValue 返回
我正在为使用 JPA 的存储库层编写集成测试。然而,每次测试后,它都会在数据库中留下大量垃圾,我想在测试结束时将其清除。我正在查看 DBUnit,它似乎能够重新初始化我的数据库。然而扩展测试用例的事情
我想尝试使用 DBUnit 进行单元测试,但我的数据集有问题。 这是我的持久性对象: @Entity @Table(name = "personnes") public class Personne
我想知道是否有一种方法可以存储和检索元表数据以及完整或平面 XML 文件,主要是有关数据库架构主键的信息。 最佳答案 dbUnit 在处理时读取数据库元数据,但不存储它。它的所有操作都是为了数据处理。
我有以下 dbunit 配置 org.codehaus.mojo dbunit-maven-plugin 1.0-beta-3
我正在使用 maven dbunit 插件(调整版本 1.0-beta-3)。 在我的 pom.xml 文件中,我定义了很少执行的插件: org.codehaus.mojo dbun
我正在尝试将 dbunit 和 spring dbunit 包含到我的项目中进行测试。我有 2 个文件夹:“src/测试/java/dao”和“src/test/resources/dao”。 在资源
看起来 DbUnit 正在使用 JDBC 元数据来确定主键字段并使用这些字段构造删除语句: delete from tbl_name where pk_field1=? and pk_field2=?
对 DBUnit 感到沮丧:(有人知道为什么我会得到下面的 dbAssertionFailedError driverClass is null 吗?dbunitData.xml 包含一行测试数据。我
我在Java7中有一个带有Spring和DbUnit 2.5.4的Java项目。 我想禁用DbUnit键检查,但仅针对其中有许多表被交叉引用的特定测试。 我尝试了此代码,但没有成功。 如何仅为此测试禁
我有一个包含 Spring + Maven + JPA (Hibernate) 的系统。我使用 Junit 和 DBUnit。我有一个带有生成 id 的实体:在测试期间它不会重置序列。我该如何解决这个
我有一个 Hibernate 实体,它与其自身具有递归关系(父子关系)。我使用 DbUnit XML 文件在测试中插入一些数据,包括关系。 但是,在我的测试中查询parent=null(根)列表的服务
我的数据库单元测试有问题,该测试测试数据是否正确保存。因此,我用我的数据创建了一个示例数据库,并尝试将设置和预期数据进行比较。 id 生成和其他一切都应该由 hibernate 管理 @RunWith
我是一名优秀的程序员,十分优秀!