我正在尝试为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这样的附加库的情况下做到这一点。
有什么建议吗?
发布于 2020-08-12 23:50:19
我会尝试用一种不同的方式来解决这个问题。提供一个模拟客户端,它将模拟right 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);
}
}//实现session接口中的某些方法的类
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客户端功能。
https://stackoverflow.com/questions/63360669
复制相似问题