草庐IT

java - junit 测试中的 spring-data-jpa bean 验证

coder 2024-03-08 原文

在我最近的工作中,我使用 spring-data-jpa 来利用提供的存储库。 当涉及到集成测试时,我无法配置(我假设)用于测试的 spring 上下文,因此 bean 验证在我的测试中不起作用。

我知道我可以注入(inject) validator ,并对我的注释进行单元测试,但事实并非如此。我正在编写集成测试,并希望测试有数据库支持的存储库。

我准备了一个简单的项目来展示所有必要的项目文件。

当我运行测试时,有 2 个失败了,我不知道为什么,hibernate validator 出现在类路径上。

Failed tests:   insertWrongEmail(com.example.core.data.jpa.UserRepositoryTest): Expected ConstraintViolationException wasn't thrown.
insertToShortPassword(com.example.core.data.jpa.UserRepositoryTest): Expected ConstraintViolationException wasn't thrown.

[..]

Apr 23, 2013 5:00:08 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 4.3.1.Final

源代码和 mvn 测试 下面的输出。

预先感谢您的帮助。

Java 类(我去掉了注释、geters、seters、equals、hashCode、toString 等):

基础实体

package com.example.core.data.jpa;

import javax.persistence.*;

@MappedSuperclass
public abstract class BaseEntity {
    public static final String SEQUENCE = "global_seq";

    @Id
    @SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
    @Column(name = "id")
    private Long id;

    public Long getId() {
        return id;
    }
}

用户

package com.example.core.data.jpa;

import javax.persistence.*;
import javax.validation.constraints.Pattern;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = "users")
@NamedQuery(name = "User.findByEmail", query = "select u from User u where upper(u.email) = :email")
public class User extends BaseEntity implements Serializable {
    private static final long serialVersionUID = 333700989750828624L;

    private static final int MAX_NAME_LENGTH = 128;
    private static final int MAX_EMAIL_LENGTH = 128;
    private static final int MAX_PASSWORD_LENGTH = 256;
    private static final int MIN_NAME_LENGTH = 6;

    private static final int EQUALS_MAGIC = 71;

    @Size(min = MIN_NAME_LENGTH)    
    @Column(name = "name", nullable = false, length = MAX_NAME_LENGTH)
    private String name;

    @Pattern(regexp = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$")
    @Column(name = "email", nullable = false, unique = true, length = MAX_EMAIL_LENGTH)
    private String email;

    @Column(name = "password", nullable = false, length = MAX_PASSWORD_LENGTH)
    private String password;

    @OneToMany(mappedBy="user", cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
    private List<Role> roles;
//geters, seters, equals, hashCode
}

作用

package com.example.core.data.jpa;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "roles")
public class Role extends BaseEntity implements Serializable {
    private static final long serialVersionUID = -2575871700366265974L;

    private static final int MAX_NAME_LENGTH = 128;

    @Column(name = "name", nullable = false, unique = true, length = MAX_NAME_LENGTH)
    private String name;

    @ManyToOne(cascade={CascadeType.ALL})
    private User user;
//geters, seters, equals, hashCode
}

用户资料库测试

package com.example.core.data.jpa;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.example.core.data.repository.UserRepository;

import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-context.xml")
@Transactional
public class UserRepositoryTest {
    @Inject
    private UserRepository userRepository;

    private User user;

    private static final String NAME = "User Name";
    private static final String EMAIL = "user_name@example.com";
    private static final String PASSWORD = "PASSWORD";

    @Before
    public void setUp() {
        user = new User(NAME, EMAIL, PASSWORD);
    }

    @Test
    public void insert() {
        //given

        //when
        User inserted = userRepository.save(user);

        //then
        assertEquals(NAME, inserted.getName());
        assertEquals(EMAIL, inserted.getEmail());
        assertEquals(PASSWORD, inserted.getPassword());
        assertNotNull(inserted.getId());
    }

    @Test
    public void insertWrongEmail() {
        //given
        user.setEmail("NOT_AN_EMAIL_ADDRESS");

        //when
        try {
            userRepository.save(user);

            fail("Expected ConstraintViolationException wasn't thrown.");

        } catch (ConstraintViolationException e) {
            //then

            assertEquals(1, e.getConstraintViolations().size());
            ConstraintViolation<?> violation =
                    e.getConstraintViolations().iterator().next();

            assertEquals("email", violation.getPropertyPath().toString());
            assertEquals(Pattern.class,
                    violation.getConstraintDescriptor()
                            .getAnnotation().annotationType());
        }
    }

    @Test
    public void insertToShortName() {
        //given
        user.setName("SHORT");

        //when
        try {
            userRepository.save(user);

            fail("Expected ConstraintViolationException wasn't thrown.");

        } catch (ConstraintViolationException e) {
        //then

            assertEquals(1, e.getConstraintViolations().size());
            ConstraintViolation<?> violation =
                    e.getConstraintViolations().iterator().next();

            assertEquals("name", violation.getPropertyPath().toString());
            assertEquals(Size.class,
                    violation.getConstraintDescriptor()
                            .getAnnotation().annotationType());
        }
    }
}

用户资料库

package com.example.core.data.repository;

import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.core.data.jpa.User;

public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>data-jpa</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Exampl core jpa package</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.java-persistence</groupId>
            <artifactId>jpa-api</artifactId>
            <version>2.0-cr-1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.1.Final</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-jdk14</artifactId>
            <version>1.6.0</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.12</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.2.2.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>2.2.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

测试上下文.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa
            http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:annotation-config/>
    <jpa:repositories base-package="com.example.core.data.repository" />
    <tx:annotation-driven transaction-manager="transactionManager" />

    <jdbc:embedded-database id="dataSource" type="HSQL"/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
            p:entityManagerFactory-ref="entityManagerFactory" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter" >
        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.example.core.data.jpa</value>
            </list>
        </property>
    </bean>

    <bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
          p:generateDdl="true" p:database="HSQL" />

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
            p:messageInterpolator-ref="messageInterpolator" p:validationMessageSource-ref="messageSource" />

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
          p:basename="classpath:I18N/messages,classpath:ValidationMessages*.properties" />

    <bean id="messageInterpolator"
          class="org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator" />
</beans>

mvn 测试 输出

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building Example core jpa package 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ data-jpa ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ data-jpa ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.5:testResources (default-testResources) @ data-jpa ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ data-jpa ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.10:test (default-test) @ data-jpa ---
[INFO] Surefire report directory: /home/[..]/data-jpa/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.example.core.data.jpa.UserRepositoryTest
Apr 23, 2013 4:39:34 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [test-context.xml]
Apr 23, 2013 4:39:35 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@3cd6ad74: startup date [Tue Apr 23 16:39:35 CEST 2013]; root of context hierarchy
Apr 23, 2013 4:39:35 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Apr 23, 2013 4:39:35 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver#423dc560' of type [class org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Apr 23, 2013 4:39:35 PM org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory initDatabase
INFO: Creating embedded database 'dataSource'
Apr 23, 2013 4:39:35 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'dataSource' of type [class org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Apr 23, 2013 4:39:35 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'dataSource' of type [class org.springframework.jdbc.datasource.SimpleDriverDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Apr 23, 2013 4:39:35 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'jpaAdapter' of type [class org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Apr 23, 2013 4:39:35 PM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'default'
Apr 23, 2013 4:39:35 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Apr 23, 2013 4:39:35 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.0.Final}
Apr 23, 2013 4:39:35 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Apr 23, 2013 4:39:35 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Apr 23, 2013 4:39:35 PM org.hibernate.ejb.Ejb3Configuration configure
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
Apr 23, 2013 4:39:36 PM org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator instantiateExplicitConnectionProvider
INFO: HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
Apr 23, 2013 4:39:36 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
Apr 23, 2013 4:39:36 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
Apr 23, 2013 4:39:36 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Apr 23, 2013 4:39:36 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 4.3.1.Final
Apr 23, 2013 4:39:37 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Apr 23, 2013 4:39:37 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Apr 23, 2013 4:39:37 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Apr 23, 2013 4:39:37 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: roles
Apr 23, 2013 4:39:37 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: users
Apr 23, 2013 4:39:37 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: roles
Apr 23, 2013 4:39:37 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: users
Apr 23, 2013 4:39:37 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: global_seq
Apr 23, 2013 4:39:37 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Apr 23, 2013 4:39:37 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'entityManagerFactory' of type [class org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Apr 23, 2013 4:39:37 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Apr 23, 2013 4:39:37 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Apr 23, 2013 4:39:37 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@69950b4: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,userRepository,org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor#0,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,dataSource,transactionManager,entityManagerFactory,jpaAdapter,validator,messageSource,messageInterpolator,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Apr 23, 2013 4:39:38 PM org.springframework.test.context.transaction.TransactionalTestExecutionListener startNewTransaction
INFO: Began transaction (1): transaction manager [org.springframework.orm.jpa.JpaTransactionManager@58eac93b]; rollback [true]
Apr 23, 2013 4:39:38 PM org.springframework.test.context.transaction.TransactionalTestExecutionListener endTransaction
INFO: Rolled back transaction after test execution for test context [TestContext@2b98919b testClass = UserRepositoryTest, testInstance = com.example.core.data.jpa.UserRepositoryTest@2d7f6d79, testMethod = insert@UserRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@8ec3a45 testClass = UserRepositoryTest, locations = '{classpath:test-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
Apr 23, 2013 4:39:38 PM org.springframework.test.context.transaction.TransactionalTestExecutionListener startNewTransaction
INFO: Began transaction (2): transaction manager [org.springframework.orm.jpa.JpaTransactionManager@58eac93b]; rollback [true]
Apr 23, 2013 4:39:38 PM org.springframework.test.context.transaction.TransactionalTestExecutionListener endTransaction
INFO: Rolled back transaction after test execution for test context [TestContext@2b98919b testClass = UserRepositoryTest, testInstance = com.example.core.data.jpa.UserRepositoryTest@1fcf7061, testMethod = insertWrongEmail@UserRepositoryTest, testException = java.lang.AssertionError: Expected ConstraintViolationException wasn't thrown., mergedContextConfiguration = [MergedContextConfiguration@8ec3a45 testClass = UserRepositoryTest, locations = '{classpath:test-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
Apr 23, 2013 4:39:38 PM org.springframework.test.context.transaction.TransactionalTestExecutionListener startNewTransaction
INFO: Began transaction (3): transaction manager [org.springframework.orm.jpa.JpaTransactionManager@58eac93b]; rollback [true]
Apr 23, 2013 4:39:38 PM org.springframework.test.context.transaction.TransactionalTestExecutionListener endTransaction
INFO: Rolled back transaction after test execution for test context [TestContext@2b98919b testClass = UserRepositoryTest, testInstance = com.example.core.data.jpa.UserRepositoryTest@168ee2a9, testMethod = insertToShortPassword@UserRepositoryTest, testException = java.lang.AssertionError: Expected ConstraintViolationException wasn't thrown., mergedContextConfiguration = [MergedContextConfiguration@8ec3a45 testClass = UserRepositoryTest, locations = '{classpath:test-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
Tests run: 3, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: 3.712 sec <<< FAILURE!

Results :

Failed tests:   insertWrongEmail(com.example.core.data.jpa.UserRepositoryTest): Expected ConstraintViolationException wasn't thrown.
  insertToShortPassword(com.example.core.data.jpa.UserRepositoryTest): Expected ConstraintViolationException wasn't thrown.

Tests run: 3, Failures: 2, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.216s
[INFO] Finished at: Tue Apr 23 16:39:38 CEST 2013
[INFO] Final Memory: 7M/245M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test (default-test) on project data-jpa: There are test failures.
[ERROR] 
[ERROR] Please refer to /home/[..]/data-jpa/target/surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Process finished with exit code 1

已解决

在@gunnar 回答后,我更改了测试以在 repository.save 之后刷新持久性上下文,它按预期工作。

对 UserRepository 的更改

//inject entity manager
@PersistenceContext
private EntityManager entityManager;

//add flush after save in test method
@Test
public void insertWrongEmail() {
    //given
    user.setEmail("NOT_AN_EMAIL_ADDRESS");

    //when
    try {
        userRepository.save(user);
        entityManager.flush();

        fail("Expected ConstraintViolationException wasn't thrown.");

方案二

在@andyb 的推荐下,我已经切换到 eclipselink 并且测试工作无需刷新。这就是我将采用的解决方案,我认为切换实现比使用变通方法更好。

最佳答案

我设法在本地重现问题中准确描述的问题,尽管是在添加回缺少的 get/set 函数和 UserRepository 类之后:-)

经过一番挖掘,我发现了两个存在的问题 JPA ConstraintViolation vs RollbackHibernate not following JPA specifications when combined with Bean Validation API?

两者似乎都得出结论,Hibernate 没有正确抛出 ConstraintValidationException

第二题的结果是缺陷HHH-8028 - entityManager.persist not throwing ConstraintValidationException针对 Hibernate 提出。

为了确认这是同一个问题,我切换到一个简单的 @GeneratedValue 并通过了 insertWrongEmailinsertToShortPassword 仍然失败,但我将其归因于密码字段中缺少的 @Size(min = 6)。添加之后,所有测试都通过了。

回到您配置的 @GeneratedValue 然后我将 Hibernate 换成 EclipseLink 持久性框架。两项测试都通过了,这似乎证实了前面问题的发现。我所做的更改是:

pom.xml 更改添加了 jpa 工件,如 EclipseLink 中所述网站

<dependency>
   <groupId>org.eclipse.persistence</groupId>
   <artifactId>org.eclipse.persistence.jpa</artifactId>
   <version>2.4.0</version>
   <scope>compile</scope>
</dependency>

test-context.xml 更改

切换到EclipseLinkJpaVendorAdapter

<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"
    p:generateDdl="true" p:database="HSQL" />

添加 eclipselink.weaving 属性,详见 EclipseLinkJpaVendorAdapter instead of HibernateJpaVendorAdapter issue

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter" >
    <!-- existing configuration is identical -->
    <property name="jpaPropertyMap">
      <map>
        <entry key="eclipselink.weaving" value="false"/>
      </map>
    </property>
</bean>

User.java 变化

我需要添加一个默认的无参数构造函数。您可能已经在完整的 User.java 类中拥有一个。

关于java - junit 测试中的 spring-data-jpa bean 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16172843/

有关java - junit 测试中的 spring-data-jpa bean 验证的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  3. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  4. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  5. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  6. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  7. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  8. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  9. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  10. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

随机推荐