Java 如何使用Mockito注入JMS依赖项
我有一个servlet,我正在为它编写测试用例,它已经工作了,但是在代码的末尾,一些JMS调用抛出了异常“javax.naming.NameNotFoundException”,我在EJB bean和datasource中也遇到了这个错误,所以我把它们注入到@BeforeClass中,现在它们工作得很好,我需要对JMS调用执行相同的操作,如下所示 我在servlet中的jms调用如下所示Java 如何使用Mockito注入JMS依赖项,java,jms,mockito,junit4,Java,Jms,Mockito,Junit4,我有一个servlet,我正在为它编写测试用例,它已经工作了,但是在代码的末尾,一些JMS调用抛出了异常“javax.naming.NameNotFoundException”,我在EJB bean和datasource中也遇到了这个错误,所以我把它们注入到@BeforeClass中,现在它们工作得很好,我需要对JMS调用执行相同的操作,如下所示 我在servlet中的jms调用如下所示 ctx=new InitialContext(); queueConnectionFact
ctx=new InitialContext();
queueConnectionFactory=(QueueConnectionFactory) ctx.lookup("jms/queueConnectionFactory");
queue=(Queue) ctx.lookup("jms/reportQueue");
queueConnection=queueConnectionFactory.createQueueConnection();
queueSession=queueConnection.createQueueSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
queueSender=queueSession.createSender(queue);
message=queueSession.createObjectMessage(etEDocRequestParams);
queueSender.send(message);
但我不知道如何在没有容器的情况下将JMS对象插入Jndi。请帮忙
我的test@beforeclass正在创建一个伪InitialContext,它用于获取数据源,并使用EJBMOCK,它也用于EJB。请看下面的代码
public class BookingSaveTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.evermind.sql.DriverManagerDataSource");
ds.setJdbcUrl("jdbc:oracle:thin:@192.168.74.49:1521:xyz");
ds.setUser("devpxyz");
ds.setPassword("pass123");
ds.setMaxPoolSize(1);
ds.setMaxPoolSize(15);
ds.setAcquireIncrement(3);
ds.setMaxStatementsPerConnection(100);
//ds.setAutomaticTestTable("c3p0_test_table");
ds.setNumHelperThreads(20);
SimpleNamingContextBuilder builder = null;
builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
builder.bind("java:comp/env/jdbc/DB", ds);
//bellow this is mocking EJB container
MockContextFactory.setAsInitial();
// Create an instance of the MockContainer and pass the JNDI context that
// it will use to bind EJBs.
MockContainer mockContainer = new MockContainer( new InitialContext() );
SessionBeanDescriptor statefulSampleDescriptor =
new SessionBeanDescriptor( "PRQSessionBean",
PRQSessionHome.class, PRQSession.class, PRQSessionBean.class );
// Mark this bean as stateful. Stateless is the default.
statefulSampleDescriptor.setStateful( true );
mockContainer.deploy( statefulSampleDescriptor );
}
..
..
..
}
您的问题不在于JMS,而在于JNDI。您需要在JNDI注册表中注册JMS模拟,如果您在应用程序服务器之外进行测试,很可能根本没有正确设置
这个问题基本上问的是同一个问题,应该可以帮助你解决这个问题:如果你不得不伪造JMS、JNDI和EJB,mockEJB提供所有这些,我没有完全阅读它,我以为它只是为了EJB。您在其中定义了所有接口的实现类,您可以轻松地将它们绑定到您的上下文。
如果您需要更多信息,请告诉我谢谢您的回复Jens,您发布的链接是针对Datasource的,我已经能够使用EJBMock为其创建一个假的InitialContext以及EJB的假容器,它们工作正常,请再次查看我的原始帖子,我做了一些改变。那样的话,我真的不理解你的问题。就像处理数据源一样:创建所需类的模拟,并像在代码中那样将其绑定到jndi上下文。我以前没有做过JMS,这些接口不能直接绑定,这就是为什么询问是否有人做过的原因。你说的“不能直接绑定”是什么意思?当你尝试时,你的电脑会爆炸吗?还是地球停止转动了?谢谢你的帮助Jens。我会在这里发布解决方案,当我找到它:)