2014-10-08 1 views
0

Приложение приносит мне ошибки при попытке его создания - оно останавливается на тесте, которое просто создает EntityManagerFactory. У меня также есть основной метод с некоторым кодом, который сохраняет объекты в базе данных, но запуск без тестов работает хорошо.Невозможно построить EntityManagerFactory в тесте JUnit

Вот Test Output

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.205 sec <<< FAILURE! 
test(sk.matejkvassay.musiclibrary.AlbumDaoImplTest) Time elapsed: 1.135 sec <<< ERROR! 
javax.persistence.PersistenceException: [PersistenceUnit: TestPU] Unable to build EntityManagerFactory 
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915) 
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890) 
    at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57) 
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63) 
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47) 
    at sk.matejkvassay.musiclibrary.AlbumDaoImplTest.test(AlbumDaoImplTest.java:37) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:483) 
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) 
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) 
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) 
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) 
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) 
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68) 
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) 
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) 
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) 
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) 
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) 
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) 
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300) 
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:483) 
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) 
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) 
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175) 
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107) 
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68) 
Caused by: org.hibernate.HibernateException: Error applying BeanValidation relational constraints 
    at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:219) 
    at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.integrate(BeanValidationIntegrator.java:126) 
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:306) 
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1744) 
    at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94) 
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905) 
    ... 34 more 
Caused by: java.lang.reflect.InvocationTargetException 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:483) 
    at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:208) 
    ... 39 more 
Caused by: org.hibernate.HibernateException: Unable to build the default ValidatorFactory 
    at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:524) 
    at org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:119) 
    ... 44 more 
Caused by: javax.validation.ValidationException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath. 
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:271) 
    at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:110) 
    at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:521) 
    ... 45 more 

тест сам по себе

public class AlbumDaoImplTest { 

    @Test 
    public void test() { 
     EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestPU"); 
     assertNotNull(emf); 
    } 
} 

Основной метод

public class Main { 

    public static void main(String[] args){ 
     EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestPU"); 
     EntityManager em = emf.createEntityManager(); 
     em.getTransaction().begin(); 

     Album album1=new Album(); 
     album1.setCommentary("Commentary commentary commentary."); 
     album1.setTitle("Album title"); 

     Genre genre1=new Genre(); 
     genre1.setName("Genre name"); 
     genre1.setDescription("Genre commentary."); 

     Song song1=new Song(); 
     Song song2=new Song(); 
     Song song3=new Song(); 

     song1.setAlbum(album1); 
     song1.setBitrate(320); 
     song1.setCommentary("Song commentary."); 
     song1.setPositionInAlbum(1); 
     song1.setTitle("Song title."); 

     song2.setAlbum(album1); 
     song2.setBitrate(320); 
     song2.setCommentary("Song commentary."); 
     song2.setPositionInAlbum(2); 
     song2.setTitle("Song title."); 

     song3.setAlbum(album1); 
     song3.setBitrate(320); 
     song3.setCommentary("Song commentary."); 
     song3.setPositionInAlbum(2); 
     song3.setTitle("Song title."); 


     HashSet<Song>songs= new HashSet<Song>(); 
     songs.add(song1); 
     songs.add(song2); 
     songs.add(song3); 
     album1.setSongs(songs); 


     em.persist(genre1); 
     em.persist(song1); 
     em.persist(song2); 
     em.persist(song3); 
     em.persist(album1); 
     em.getTransaction().commit(); 
     em.close(); 
     emf.close(); 
    } 
} 

persistence.xml

<?xml version="1.0" encoding="UTF-8"?> 
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/ persistence http://java.sun.com/xml/ns/persistence/ persistence_1_0.xsd"> 
    <persistence-unit name="TestPU" transaction-type="RESOURCE_LOCAL"> 
    <provider>org.hibernate.ejb.HibernatePersistence</provider> 
    <properties> 
     <property name="hibernate.connection.username" value="testUser"/> 
     <property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/> 
     <property name="hibernate.connection.password" value="testUser123"/> 
     <property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/musicLibraryTestDB"/> 
     <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/> 
     <property name="hibernate.hbm2ddl.auto" value="update"/> 
     <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" /> 
     <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/> 
    </properties> 
</persistence> 

pom.xml

<?xml version="1.0" encoding="UTF-8"?> 
<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/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>sk.matejkvassay</groupId> 
    <artifactId>MusicLibrary</artifactId> 
    <version>1.0-SNAPSHOT</version> 
    <packaging>war</packaging> 

    <name>MusicLibrary</name> 

    <properties> 
     <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> 
     <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> 
      <type>jar</type> 
     </dependency> 
     <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>4.10</version> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>javax</groupId> 
      <artifactId>javaee-web-api</artifactId> 
      <version>7.0</version> 
      <type>jar</type> 
      <scope>provided</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.hibernate</groupId> 
      <artifactId>hibernate-entitymanager</artifactId> 
      <version>4.1.4.Final</version>  
     </dependency> 

     <dependency> 
      <groupId>org.apache.derby</groupId> 
      <artifactId>derbyclient</artifactId> 
      <version>10.7.1.1</version>   
     </dependency> 
    </dependencies> 

    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-compiler-plugin</artifactId> 
       <version>3.1</version> 
       <configuration> 
        <source>1.7</source> 
        <target>1.7</target> 
        <compilerArguments> 
         <endorseddirs>${endorsed.dir}</endorseddirs> 
        </compilerArguments> 
       </configuration> 
      </plugin> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-war-plugin</artifactId> 
       <version>2.3</version> 
       <configuration> 
        <failOnMissingWebXml>false</failOnMissingWebXml> 
       </configuration> 
      </plugin> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-dependency-plugin</artifactId> 
       <version>2.6</version> 
       <executions> 
        <execution> 
         <phase>validate</phase> 
         <goals> 
          <goal>copy</goal> 
         </goals> 
         <configuration> 
          <outputDirectory>${endorsed.dir}</outputDirectory> 
          <silent>true</silent> 
          <artifactItems> 
           <artifactItem> 
            <groupId>javax</groupId> 
            <artifactId>javaee-endorsed-api</artifactId> 
            <version>7.0</version> 
            <type>jar</type> 
           </artifactItem> 
          </artifactItems> 
         </configuration> 
        </execution> 
       </executions> 
      </plugin> 
     </plugins> 
    </build> 

</project> 

ответ

0

На основе представленной трассировки стека вы недостающую зависимость для проверки компонента.

Попробуйте добавить гибернации-валидатор как зависимость в вашем pom.xml:

<dependency> 
    <groupId>org.hibernate</groupId> 
    <artifactId>hibernate-validator</artifactId> 
    <version>5.1.2.Final</version> 
</dependency> 
+0

Спасибо, это сработало. Хотелось бы, чтобы я спросил раньше, потратил на это больше времени, чем я хотел бы признать. – Matthew