我有以下单元测试,它给了我一个空指针异常。调试器转到创建连接工厂的行之后的 finally 块。 这是测试:
@Test
public void receiveMessage() throws Exception {
MessageConsumer consumer = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
try {
connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
connection = connectionFactory.createConnection("username","pwd");
connection.start();
session = connection.createSession(true,
Session.AUTO_ACKNOWLEDGE);
destination = session
.createQueue("myQueue");
logger.info("Starting consumer");
consumer = session
.createConsumer(destination);
Message m = consumer.receive();
logger.info("Received message:" + m);
}
} catch (Exception e) {
logger.error("", e);
} finally {
consumer.close();
session.close();
connection.stop();
connection.close();
}
}
下面是堆栈跟踪:
java.lang.NullPointerException at ClassName.receiveMessage(ClassName.java:62( 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( 在 org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12( 在 org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44( 在 org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17( 在 org.junit.internal.runners.statement.RunAfters.evaluate(RunAfters.java:27( at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271( at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70( 在 org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.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.run(JUnit4TestReference.java:50( 在 org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38( 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459( 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675( 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382( 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192
(
在单元测试中,不应使用实际连接,即您尝试在单元测试用例中连接到 BrokerURL,这不是单元测试的目的。
在这种情况下,您需要使用诸如Easymock+Powermock
或Mockito
之类的库来模拟外部连接
关于空指针异常,您的经纪人是否启动? 和用户名,密码正确,请检查这些