Mockito在向activeMQ onMessage()发送消息时测试用例出错

时间:2016-10-24 04:29:48

标签: java unit-testing junit mockito activemq

我使用Mockito使用ActiveMQ和单元测试用例编写应用程序,其中我有一个异步onMessage()侦听器和一个测试它的方法。如果在onMessage()中添加任何if条件,测试用例将失败。避免这个

代码段如下

Main.java

//Initialize boolean here
    boolean flag=false;

    public void onMessage(final Message message) {

                    //getting error in the below if condition
                    if(flag) //Not executing at all Null pointer here
                    {
                            if (!(message instanceof TextMessage)) {
                               //Log error
                            }
                            try {
                                final String messageType = message.getStringProperty("messageType");
                                _LOG.info("The MessageType is {}", messageType);
                                final String msg = ((TextMessage) message).getText();
                                _LOG.debug(msg);
                            } catch (final JMSException e) {
                                _LOG.error("We could not read the message", e);
                            }
                    }
                    else  //not able to execute if or else conditions
                    {
                        //do Something else
                    }
               }

MockTest.java

        //Call Main here
         @InjectMocks
         private Main listener;

        @Test
            public void shouldProcessMessage() throws JMSException {

                final String messageType = "Hello";
                final String messageBody ="Hi";
                final ActiveMQTextMessage message = new ActiveMQTextMessage();
                message.setStringProperty("messageType", messageType);
                message.setText(messageBody);

                // The below line does not execute at all
                // iam getting null pointer exception here
                listener.onMessage(message);
            }

1 个答案:

答案 0 :(得分:0)

布尔值flag是否已在此类的某处实例化?

如果您正在获得NPE,可能是因为您尚未实例化flag变量。