问题描述
我正在尝试为MDB编写单元测试。我测试的目的是确保MDB中的逻辑可以识别ObjectMessage
中对象的正确类型并对其进行处理。但是,我不知道如何制作ObjectMessage
,因此可以对其进行测试。我不断收到空指针异常。
这是我的单元测试:
/**
* Test of the logic in the MDB
*/
@RunWith(JMockit.class)
@ExtendWith(TimingExtension.class)
class MDBTest
{
protected MyMDB mdb;
@BeforeEach
public void setup() throws NamingException,CreateHeaderException,DatatypeConfigurationException,PropertiesDataException
{
mdb = new MyMDB();
}
/**
* Test the processing of the messages by the MDB
*/
@Test
void testReceivingMessage() throws JMSException,IOException
{
MyFirstObject testMsg = getTestMessage();
ObjectMessage msg = null;
Session session = null;
new MockUp<ObjectMessage>()
{
@Mock
public void $init()
{
}
@Mock
public Serializable getobject()
{
return testMsg;
}
};
new MockUp<Session>()
{
@Mock
public void $init()
{
}
@Mock
public ObjectMessage createObjectMessage(Serializable object)
{
return msg;
}
};
// !!!! Null pointer here on Session !!!!
ObjectMessage msgToSend = session.createObjectMessage(testMsg);
mdb.onMessage(msgToSend);
assertEquals(1,mdb.getNumMyFirstObjectMsgs());
}
/**
* Create a Test Message
*
* @return the test message
* @throws IOException
*/
protected MyFirstObject getTestMessage) throws IOException
{
MyFirstObject myObj = new MyFirstObject();
myObj.id = 0123;
myObj.description = "TestMessage";
return myObj;
}
}
我觉得我应该能够以某种方式初始化Session
,但是我无需使用其他类似Mockrunner的库就可以这样做。
有什么建议吗?
解决方法
我会尝试以其他方式解决这个问题。提供一个模拟客户端,该客户端仅模拟正确的API 。
我们应该仅模拟消息检索和处理所需的一组功能,但这意味着我们可能必须为EJB / JMS库中可用的某些API提供自定义实现。模拟客户端将具有在给定主题/队列/频道上推送消息的功能,消息可以是简单的字符串。
一个简单的实现可能看起来像这样,为简单起见,其他方法已被省略。
// JMSClientImpl is an implementation of Connection interface.
public class MyJmsTestClient extends JMSClientImpl{
Map<String,String> channelToMessage = new ConcurrentHashMap<>();
public Map<String,String> getMessageMap(){
return channelToMessage;
}
public void enqueMessage(String channel,String message){
channelToMessage.put(channe,message);
}
@Override
public Session createSession(){
return new MyTestSession(this);
}
}
//一个通过会话接口实现某些方法的类
public MyTestSession extends SessionImpl{
private MyJmsTestClient jmsClient;
MyTestSession(MyJmsTestClient jmsClient){
this.jmsClient = jmsClient;
}
// override methods that fetches messages from remote JMS
// Here you can just return messages from MyJmsTestClient
// override other necessary methods like ack/nack etc
MessageConsumer createConsumer(Destination destination) throws JMSException{
// returns a test consume
}
}
从MessageConsumer接口实现方法的类
class TestMessageConsumer extends MessageConsumerImpl {
private MyJmsTestClient jmsClient;
private Destination destination;
TestMessageConsumer(MyJmsTestClient jmsClient,Destination destination){
this.jmsClient = jmsClient;
this.destination = destination;
}
Message receive() throws JMSException{
//return message from client
}
}
没有直接的方法,您可以查看是否有任何库可以为您提供嵌入式JMS客户端功能。