10071

JBoss Embedded jUnit testing for EJB : NameNotFoundException

Question:

I'm newbie in EJB and jUnit, and I'm trying to do Embedded testing for the simple EJB-project that running by jBoss AS 7.1.1.Final.

I've written this test:

package com.staff.test.logic; import java.io.File; import javax.ejb.embeddable.EJBContainer; import javax.naming.Context; import javax.naming.NamingException; import org.jboss.as.embedded.EmbeddedServerFactory; import org.jboss.as.embedded.StandaloneServer; import org.junit.Before; import org.junit.Test; import com.staff.main.logic.ProjectBean; public class ProjectBeanTest { private StandaloneServer server; private static EJBContainer ec; private static Context ctx; @Before public void initContainer() throws Exception { String jbossHomeDir = System.getenv("JBOSS_HOME"); System.setProperty("jboss.home","C:/eclipse/jboss-as-7.1.1.Final"); assert jbossHomeDir != null; server = EmbeddedServerFactory.create(new File(jbossHomeDir), System.getProperties(), System.getenv(), "org.jboss.logmanager"); server.start(); ctx=server.getContext(); } // @After // public static void closeContainer() throws Exception { // if (ec != null) { // ec.close(); // } // } @Test public void test() throws NamingException { ProjectBean bean = (ProjectBean) ctx.lookup("java:global/ProjectBean"); } }

But string

<blockquote>

ProjectBean bean = (ProjectBean) ctx.lookup("java:global/ProjectBean") make exception:

</blockquote>

do this exception:

javax.naming.NameNotFoundException: ProjectBean -- service jboss.naming.context.java.global.ProjectBean at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBa sedNamingStore.java:97) at org.jboss.as.naming.NamingContext.lookup(NamingContext.java: 178) at org.jboss.as.naming.InitialContext.lookup(InitialContext.jav a:123) at org.jboss.as.naming.NamingContext.lookup(NamingContext.java: 214) at javax.naming.InitialContext.lookup(Unknown Source) at com.staff.test.logic.ProjectBeanTest.test(ProjectBeanTest.ja va:80) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall( FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(Refl ectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(Fr ameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate( InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(Ru nBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit 4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit 4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java: 63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java :236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java: 53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java: 229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.r un(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(Test Execution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTe sts(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTe sts(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(R emoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main( RemoteTestRunner.java:197)

I dont understand why this string do exception, because I'm newbie.

My project have a bean "ProjectBean" with interface "ProjectBeanLocal" and an entity "Post". And I have a file persistence.xml to work with Oracle 10g.

ProjectBean:

package com.staff.main.logic; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; import com.staff.main.domain.Post; /** * Session Bean implementation class ProjectBean */ @Stateless @LocalBean public class ProjectBean implements ProjectBeanLocal { @PersistenceContext(unitName="StaffPU") EntityManager manager; public ProjectBean() { Ejb3Configuration cfg = new Ejb3Configuration(); cfg.configure("StaffPU", null); SchemaExport schemaExport = new SchemaExport(cfg.getHibernateConfiguration()); //schemaExport.setOutputFile("schema.sql"); schemaExport.create(true, true); } @Override public void savePost(Post post){ manager.persist(post); } @Override public Post findPost(long id) { Post post=manager.find(Post.class, id); return post; } }

Interface ProjectBeanLocal:

package com.staff.main.logic; import javax.ejb.Local; import com.staff.main.domain.Post; @Local public interface ProjectBeanLocal { void savePost(Post post); Post findPost(long id); }

Entity "Post":

package com.staff.main.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; @Entity public class Post implements Serializable{ private static final long serialVersionUID = 6767319776206583629L; @Id @SequenceGenerator(name="ent2seq",sequenceName="seq_post") @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="ent2seq") private long id; @Column(nullable=false) private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

And persistence.xml:

<?xml version="1.0" encoding="UTF-8"?> <persistence 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" version="1.0"> <persistence-unit name="StaffPU"> <jta-data-source>java:jboss/datasources/OracleDS</jta-data-source> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/> <property name="hibernate.hbm2ddl.auto" value="create" /> <!-- <property name="javax.persistence.jdbc.show_sql" value="true" /> --> <!-- <property name="hibernate.show_sql" value="true" /> --> </properties> </persistence-unit> </persistence>

Answer1:

You need to expose your bean with a <a href="http://docs.oracle.com/javaee/6/tutorial/doc/gipjf.html#gipiu" rel="nofollow">Remote</a> interface.

After that, you probably will need to change the JNDI entry name used to lookup the ejb reference. You don't provide information about how the bean is deployed which, among other things, determines the binding name, but you can search the correct lookup string in the server log.

Answer2:

import java.io.File; import javax.naming.InitialContext; import org.jboss.ejb3.embedded.EJB3StandaloneBootstrap; import org.jboss.ejb3.embedded.EJB3StandaloneDeployer;

in your pom you have to add :

<dependency> <groupId>org.jboss.embedded</groupId> <artifactId>jboss-embedded-all</artifactId> <version>beta3.SP9</version> </dependency> <dependency> <groupId>org.jboss.embedded</groupId> <artifactId>thirdparty-all</artifactId> <version>beta3.SP9</version> </dependency>

you have to add :

<ol><li>embedded-jboss-beans.xml</li> <li>bean.xml,default.persistence.properties</li> <li>

ejb3-interceptors-aop.xml into your resources folder and jndi.properties too whtch contains :

java.naming.factory.initial=org.jnp.interfaces.LocalOnlyContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

and you test class must contains :

EJB3StandaloneBootstrap.boot(null); EJB3StandaloneBootstrap.scanClasspath(); EJB3StandaloneBootstrap.deployXmlResource(embeded.xml) deployer = EJB3StandaloneBootstrap.createDeployer(); deployer.getArchives().add(new File("target/classes").toURI().toURL()); deployer.create(); deployer.start(); InitialContext context = new InitialContext();

</li> </ol>

and you look up your ejb

Recommend

  • Spring Transactional not working
  • Sling model unit tests: mock currentPage in SlingHttpServletRequest
  • Help configuring MSpec
  • Mockito java.lang.Exception: Class should be public when I use inner classes in tests
  • Testing with Robolectric in Eclipse
  • Problem using MockRoundtrip class
  • Mocking service in Spring Boot
  • Mock Retrofit service with Mockito causes ExceptionInInitializerError
  • How to Filter ListAdapter using getFilter() within a fragment
  • Android - VerifyError
  • jhipster run embedded jar with prod profile - issue with liquibase
  • Cassandra NoClassDefFoundError: com/google/common/util/concurrent/AsyncFunction
  • Invert string in Rust
  • What does certain JVM do after loading ByteCode into memory?
  • Glassfish - java.lang.NoClassDefFoundError
  • What is the undocumented SessionIdInterface in PHP 5.5?
  • Embedded Glassfish JPA Datasource connection fail
  • aapt.exe'' finished with non-zero exit value 1
  • URLConnection doesn't work since API 10 and higher?
  • Android app gives error “BatteryStatsImpl: reading network stats”
  • Access variable of ScriptContext using Nashorn JavaScript Engine (Java 8)
  • What does 'Language neutral' mean with regard to MAKELANGID?
  • How to run “Deployd” on port 80 instead of port 5000 in webserver.
  • Problem deserializing objects from cache on MyBatis 3/Java
  • JQuery Internet Explorer and ajaxstop
  • Use of this Javascript
  • The plugin 'org.apache.maven.plugins:maven-jboss-as-plugin' does not exist or no valid ver
  • SignalR .NET Client Invoke throws an exception
  • Display issues when we change from one jquery mobile page to another in firefox
  • Python - Map / Reduce - How do I read JSON specific field in using DISCO count words example
  • Hibernate gives error error as “Access to DialectResolutionInfo cannot be null when 'hibernate.
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • coudnt use logback because of log4j
  • MATLAB: Piecewise function in curve fitting toolbox using fittype
  • Programmatically clearing map cache
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Binding checkboxes to object values in AngularJs
  • How can I use `wmic` in a Windows PE script?