运行 JUnit 测试时出错(JPA、Derby、Hibernate、Guice)
我正在尝试为我的 DAO 对象创建 JUnit 测试。 JUnit 直接从 Netbeans 运行。我对其中一些技术还很陌生,因此我花了很多时间来追踪我的错误来自哪里。我的代码和我看到的相应错误是:
2011 年 7 月 22 日下午 7:09:09 com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl findDerbyClient 信息:找不到 javadb 客户端 jar 文件,derby jdbc 默认情况下驱动程序不可用。致命的 [DatasourceConnectionProvider] - 找不到数据源:Waylon org.omg.CORBA.COMM_FAILURE:良好:IOP00410001:连接失败: 套接字类型:IIOP_CLEAR_TEXT;主机名:本地主机;端口:3700 vmcid: OMG 次要代码:1 已完成:无 javax.naming.NamingException:Lookup 'Waylon' 失败 SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl} [根异常是javax.naming.NamingException:无法获取 SerialContextProvider 用于 SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl} [根异常是 org.omg.CORBA.COMM_FAILURE:很好:IOP00410001: 连接失败:socketType:IIOP_CLEAR_TEXT;主机名:本地主机; 端口:3700 vmcid:OMG 次要代码:1 已完成:否]] 位于 sun.reflect.GenerateConstructorAccessor31.newInstance(来源未知) 在 com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518) 在 sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) 在 com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455) 在 java.lang.reflect.Constructor.newInstance(Constructor.java:513) 在 javax.naming.InitialContext.lookup(InitialContext.java:392) 处 com.sun.corba.ee.spi.orbutil.logex.corba.CorbaExtension.makeException(CorbaExtension.java:248) 在 com.sun.corba.ee.spi.orbutil.logex.corba.CorbaExtension.makeException(CorbaExtension.java:95) 在 org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52) 在 com.sun.corba.ee.spi.orbutil.logex.WrapperGenerator.handleFullLogging(WrapperGenerator.java:387) 在 org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124) 在 com.sun.corba.ee.spi.orbutil.logex.WrapperGenerator.access$400(WrapperGenerator.java:107) 在 org.hibernate.ejb.InjectionSettingsFactory.createConnectionProvider(InjectionSettingsFactory.java:29) 在 com.sun.corba.ee.spi.orbutil.logex.WrapperGenerator$2.invoke(WrapperGenerator.java:511) 在 org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62) 在 com.sun.corba.ee.spi.orbutil.proxy.CompositeInitationHandlerImpl.invoke(CompositeInitationHandlerImpl.java:99) 在 org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009) 在 $Proxy40.connectFailure(来源不明) org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292) 在 com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl。(SocketOrChannelConnectionImpl.java:257) 在 org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859) 在 com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl。(SocketOrChannelConnectionImpl.java:270) 在 org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669) 在 com.sun.corba.ee.impl.transport.SocketOrChannelContactInfoImpl.createConnection(SocketOrChannelContactInfoImpl.java:129) 在 com.sun.corba.ee.impl.protocol.CorbaClientRequestDispatcherImpl.beginRequest(CorbaClientRequestDispatcherImpl.java:223) 在 org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:126) 在 com.sun.corba.ee.impl.protocol.CorbaClientDelegateImpl.request(CorbaClientDelegateImpl.java:228) 在javax.persistence.Persistence.createEntityManagerFactory(未知 来源)于 com.sun.corba.ee.impl.protocol.CorbaClientDelegateImpl.is_a(CorbaClientDelegateImpl.java:393) 在 org.omg.CORBA.portable.ObjectImpl._is_a(ObjectImpl.java:112) 处 javax.persistence.Persistence.createEntityManagerFactory(未知 来源)于 org.omg.CosNaming.NamingContextHelper.narrow(NamingContextHelper.java:69) 在 com.google.inject.persist.jpa.JpaPersistService.start(JpaPersistService.java:94) 在 com.sun.enterprise.naming.impl.SerialContext$ProviderCacheKey.getNameService(SerialContext.java:1241) 在 waylon.label.LabelDAOIJTest.setUpClass(LabelDAOIJTest.java:36) 在 com.sun.enterprise.naming.impl.SerialContext.getRemoteProvider(SerialContext.java:411) 在 com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:347) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法) 处 com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:504) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 在 com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 在 javax.naming.InitialContext.lookup(InitialContext.java:392) 处 java.lang.reflect.Method.invoke(Method.java:597) 在 org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52) 在 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) 在 org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124) 在 org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) 在 org.hibernate.ejb.InjectionSettingsFactory.createConnectionProvider(InjectionSettingsFactory.java:29) 在 org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62) 在 org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) 在 org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009) 在 org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27) 在 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292) 在 org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) 在 org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859) 在 org.junit.runners.ParentRunner.run(ParentRunner.java:303) 处 org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669) 在junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39) 在 org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:126) 在 org.apache.tools.ant.taskdefs.可选.junit.JUnitTestRunner.run(JUnitTestRunner.java:518) 在javax.persistence.Persistence.createEntityManagerFactory(未知 来源)位于 org.apache.tools.ant.taskdefs.可选.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052) 在 org.apache.tools.ant.taskdefs.可选.junit.JUnitTestRunner.main(JUnitTestRunner.java:906) 在javax.persistence.Persistence.createEntityManagerFactory(未知 来源)于 com.google.inject.persist.jpa.JpaPersistService.start(JpaPersistService.java:94) 在 waylon.label.LabelDAOIJTest.setUpClass(LabelDAOIJTest.java:36) 引起原因:javax.naming.NamingException:无法获取 SerialContextProvider 用于 SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl} [根异常是 org.omg.CORBA.COMM_FAILURE:很好:IOP00410001: 连接失败:socketType:IIOP_CLEAR_TEXT;主机名:本地主机; 端口:3700 vmcid:OMG 次要代码:1 已完成:否] 在 sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法) at com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:352) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 在 com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:504) ... 29 更多在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="WaylonPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>Waylon</jta-data-source>
<class>waylon.label.Label</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
我的 DAO 正在测试:
package waylon.label.impl;
import com.google.inject.Inject;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import waylon.label.Label;
import waylon.label.LabelDAO;
/**
* {@inheritDoc}
*/
public class LabelDAOImpl implements LabelDAO {
private final EntityManager em;
@Inject
public LabelDAOImpl( EntityManager em ) {
this.em = em;
}
/**
* {@inheritDoc}
*/
@Override
public List<Label> getAllLabels() throws Exception {
TypedQuery<Label> typedQuery = em.createQuery(
"SELECT * from LABEL", Label.class );
return typedQuery.getResultList();
}
/**
* {@inheritDoc}
*/
@Override
public Label createLabel(String name) throws Exception {
em.getTransaction().begin();
Label label = new Label();
label.setName( name );
em.persist( label );
em.getTransaction().commit();
return label;
}
/**
* {@inheritDoc}
*/
@Override
public void removeLabel(String name) throws Exception {
Label label = getLabel( name );
removeLabel( label );
}
/**
* {@inheritDoc}
*/
@Override
public Label getLabel(String name) throws Exception {
Label label = em.find( Label.class, name );
return label;
}
/**
* {@inheritDoc}
*/
@Override
public void removeLabel(Label label) throws Exception {
if ( null != label ) {
em.getTransaction().begin();
em.remove( label );
em.getTransaction().commit();
}
}
}
我的 JUnit 测试:
package waylon.label;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.jpa.JpaPersistModule;
import java.util.List;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import org.hamcrest.core.IsEqual;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import waylon.label.impl.LabelDAOModule;
/**
* A JUnit Test to test our database connection and JPA code.
* @author Benjamin Bays
*/
public class LabelDAOIJTest {
private LabelDAO objectInTest = null;
private static final String PUNIT = "WaylonPU";
private static Injector injector = null;
private static PersistService persistService = null;
@BeforeClass
public static void setUpClass() throws Exception {
injector = Guice.createInjector(
new JpaPersistModule(PUNIT),
new LabelDAOModule() );
persistService = injector.getInstance( PersistService.class );
persistService.start();
}
@AfterClass
public static void tearDownClass() throws Exception {
persistService.stop();
}
@Before
public void setUp() {
objectInTest = injector.getInstance( LabelDAO.class );
}
@Test
public void doEverything() throws Exception {
final String testName = "Test Label";
Label label1 = objectInTest.createLabel( testName );
assertThat( label1.getName(), IsEqual.equalTo( testName ) );
Label label2 = objectInTest.getLabel(testName);
assertThat( label2.getName(), IsEqual.equalTo( testName ) );
final String testName3 = "Test Label3";
Label label3 = objectInTest.createLabel( testName3 );
assertThat( label3.getName(), IsEqual.equalTo( testName3 ) );
List<Label> allLabels = objectInTest.getAllLabels();
assertThat( allLabels, hasItems( label1, label3 ) );
objectInTest.removeLabel( label1 );
objectInTest.removeLabel( testName3 );
List<Label> noLabels = objectInTest.getAllLabels();
assertThat( noLabels.size(), IsEqual.equalTo( 0 ) );
}
}
任何帮助将不胜感激。谢谢。
I'm attempting to create a JUnit test for my DAO object. The JUnit is ran directly from Netbeans. I'm quite new to several of these technologies, and as a result I'm having a heck of a time tracing down where my errors are coming from. My code and the corresponding error that I'm seeing are:
Jul 22, 2011 7:09:09 PM
com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl
findDerbyClient INFO: Cannot find javadb client jar file, derby jdbc
driver will not be available by default. FATAL
[DatasourceConnectionProvider] - Could not find datasource: Waylon
org.omg.CORBA.COMM_FAILURE: FINE: IOP00410001: Connection failure:
socketType: IIOP_CLEAR_TEXT; hostname: localhost; port: 3700 vmcid:
OMG minor code: 1 completed: No javax.naming.NamingException: Lookup
failed for 'Waylon' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl}
[Root exception is javax.naming.NamingException: Unable to acquire
SerialContextProvider for
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl}
[Root exception is org.omg.CORBA.COMM_FAILURE: FINE: IOP00410001:
Connection failure: socketType: IIOP_CLEAR_TEXT; hostname: localhost;
port: 3700 vmcid: OMG minor code: 1 completed: No]] at
sun.reflect.GeneratedConstructorAccessor31.newInstance(Unknown Source)
at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
com.sun.corba.ee.spi.orbutil.logex.corba.CorbaExtension.makeException(CorbaExtension.java:248)
at
com.sun.corba.ee.spi.orbutil.logex.corba.CorbaExtension.makeException(CorbaExtension.java:95)
at
org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)
at
com.sun.corba.ee.spi.orbutil.logex.WrapperGenerator.handleFullLogging(WrapperGenerator.java:387)
at
org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
at
com.sun.corba.ee.spi.orbutil.logex.WrapperGenerator.access$400(WrapperGenerator.java:107)
at
org.hibernate.ejb.InjectionSettingsFactory.createConnectionProvider(InjectionSettingsFactory.java:29)
at
com.sun.corba.ee.spi.orbutil.logex.WrapperGenerator$2.invoke(WrapperGenerator.java:511)
at
org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62)
at
com.sun.corba.ee.spi.orbutil.proxy.CompositeInvocationHandlerImpl.invoke(CompositeInvocationHandlerImpl.java:99)
at
org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
at $Proxy40.connectFailure(Unknown Source) at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
at
com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.(SocketOrChannelConnectionImpl.java:257)
at
org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at
com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.(SocketOrChannelConnectionImpl.java:270)
at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
at
com.sun.corba.ee.impl.transport.SocketOrChannelContactInfoImpl.createConnection(SocketOrChannelContactInfoImpl.java:129)
at
com.sun.corba.ee.impl.protocol.CorbaClientRequestDispatcherImpl.beginRequest(CorbaClientRequestDispatcherImpl.java:223)
at
org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:126)
at
com.sun.corba.ee.impl.protocol.CorbaClientDelegateImpl.request(CorbaClientDelegateImpl.java:228)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
com.sun.corba.ee.impl.protocol.CorbaClientDelegateImpl.is_a(CorbaClientDelegateImpl.java:393)
at org.omg.CORBA.portable.ObjectImpl._is_a(ObjectImpl.java:112) at
javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
org.omg.CosNaming.NamingContextHelper.narrow(NamingContextHelper.java:69)
at
com.google.inject.persist.jpa.JpaPersistService.start(JpaPersistService.java:94)
at
com.sun.enterprise.naming.impl.SerialContext$ProviderCacheKey.getNameService(SerialContext.java:1241)
at waylon.label.LabelDAOIJTest.setUpClass(LabelDAOIJTest.java:36) at
com.sun.enterprise.naming.impl.SerialContext.getRemoteProvider(SerialContext.java:411)
at
com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:347)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:504)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
java.lang.reflect.Method.invoke(Method.java:597) at
org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)
at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at
org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at
org.hibernate.ejb.InjectionSettingsFactory.createConnectionProvider(InjectionSettingsFactory.java:29)
at
org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at
org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at
org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at org.junit.runners.ParentRunner.run(ParentRunner.java:303) at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39)
at
org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:126)
at
org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:518)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052)
at
org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:906)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
com.google.inject.persist.jpa.JpaPersistService.start(JpaPersistService.java:94)
at waylon.label.LabelDAOIJTest.setUpClass(LabelDAOIJTest.java:36)
Caused by: javax.naming.NamingException: Unable to acquire
SerialContextProvider for
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl}
[Root exception is org.omg.CORBA.COMM_FAILURE: FINE: IOP00410001:
Connection failure: socketType: IIOP_CLEAR_TEXT; hostname: localhost;
port: 3700 vmcid: OMG minor code: 1 completed: No] at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:352)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:504)
... 29 more at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="WaylonPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>Waylon</jta-data-source>
<class>waylon.label.Label</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
My DAO under Test:
package waylon.label.impl;
import com.google.inject.Inject;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import waylon.label.Label;
import waylon.label.LabelDAO;
/**
* {@inheritDoc}
*/
public class LabelDAOImpl implements LabelDAO {
private final EntityManager em;
@Inject
public LabelDAOImpl( EntityManager em ) {
this.em = em;
}
/**
* {@inheritDoc}
*/
@Override
public List<Label> getAllLabels() throws Exception {
TypedQuery<Label> typedQuery = em.createQuery(
"SELECT * from LABEL", Label.class );
return typedQuery.getResultList();
}
/**
* {@inheritDoc}
*/
@Override
public Label createLabel(String name) throws Exception {
em.getTransaction().begin();
Label label = new Label();
label.setName( name );
em.persist( label );
em.getTransaction().commit();
return label;
}
/**
* {@inheritDoc}
*/
@Override
public void removeLabel(String name) throws Exception {
Label label = getLabel( name );
removeLabel( label );
}
/**
* {@inheritDoc}
*/
@Override
public Label getLabel(String name) throws Exception {
Label label = em.find( Label.class, name );
return label;
}
/**
* {@inheritDoc}
*/
@Override
public void removeLabel(Label label) throws Exception {
if ( null != label ) {
em.getTransaction().begin();
em.remove( label );
em.getTransaction().commit();
}
}
}
My JUnit Test:
package waylon.label;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.jpa.JpaPersistModule;
import java.util.List;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import org.hamcrest.core.IsEqual;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import waylon.label.impl.LabelDAOModule;
/**
* A JUnit Test to test our database connection and JPA code.
* @author Benjamin Bays
*/
public class LabelDAOIJTest {
private LabelDAO objectInTest = null;
private static final String PUNIT = "WaylonPU";
private static Injector injector = null;
private static PersistService persistService = null;
@BeforeClass
public static void setUpClass() throws Exception {
injector = Guice.createInjector(
new JpaPersistModule(PUNIT),
new LabelDAOModule() );
persistService = injector.getInstance( PersistService.class );
persistService.start();
}
@AfterClass
public static void tearDownClass() throws Exception {
persistService.stop();
}
@Before
public void setUp() {
objectInTest = injector.getInstance( LabelDAO.class );
}
@Test
public void doEverything() throws Exception {
final String testName = "Test Label";
Label label1 = objectInTest.createLabel( testName );
assertThat( label1.getName(), IsEqual.equalTo( testName ) );
Label label2 = objectInTest.getLabel(testName);
assertThat( label2.getName(), IsEqual.equalTo( testName ) );
final String testName3 = "Test Label3";
Label label3 = objectInTest.createLabel( testName3 );
assertThat( label3.getName(), IsEqual.equalTo( testName3 ) );
List<Label> allLabels = objectInTest.getAllLabels();
assertThat( allLabels, hasItems( label1, label3 ) );
objectInTest.removeLabel( label1 );
objectInTest.removeLabel( testName3 );
List<Label> noLabels = objectInTest.getAllLabels();
assertThat( noLabels.size(), IsEqual.equalTo( 0 ) );
}
}
Any help would be greatly appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这花了很长时间才弄清楚。我认为这里的总体教训是一次只学习一项新技术。我提供了运行 JUnit 所采取的一系列步骤,但总的来说,RTFM 解决了几个错误。
为了给予应得的信任,这些资源发挥了巨大的作用。
我首先使用第一个资源重新创建数据库服务。这涉及到重新创建每个表并重新建立外键依赖关系(很烦人,但很有必要)。
然后,我按照第二个教程让 netbeans 自动从我的数据库表生成一个实体。我的实体不需要任何更改,但这确实导致 Netbeans 生成 persistence.xml。我将它与我自己的进行比较,并提出了这个片段:
这里的大变化是:
最后,我的单元测试运行了,万岁!为了解决这个问题,我的生产代码中存在错误(因为我是 JPA 的初学者)。我所做的更改是针对 LabelDAOImpl.java。我了解到 SELECT * 在 JPA 中不起作用:)
This took a long time to figure out. I think the overall lesson here is to learn only one new technology at a time. I've provided the series of steps I took to get my JUnits to run, but overall it was several mistakes that were resolved by RTFM.
To give credit where it is due, these resources helped tremendously.
I started by recreating my database service using the first resource. This involved recreating each table and reestablishing the foreign key dependencies (annoying, but necessary).
I then followed the second tutorial to have netbeans automatically generate an Entity from my database table. My entity required no changes, but this did cause Netbeans to generate a persistence.xml. I compared it against my own, and came up with with this segment:
The big changes here are:
Finally, my unit test ran, hooray! Just to round things out, there were errors in my production code (because I'm a total beginner at JPA). The changes I made were to LabelDAOImpl.java. I learned that SELECT * doesn't work in JPA :)
如果您使用的是 spring,请确保您的应用程序上下文已正确解析。比如为测试激活适当的弹簧轮廓。
这对我有用
If you are using spring, Make sure you have your application context resolved properly. Like activate appropriate spring profile for the test.
That worked for me