Mockito方法为使用的变量抛出空指针异常

时间:2016-09-21 06:13:38

标签: java java-ee junit mockito

我使用mockito进行测试,而且非常新的。    我在Mockito方法和Onmessage方法中获得了一个空指针异常,用于使用声明的对象/变量。    代码段如下所示。

Class A.java

        Class A{

        @Inject
        CheckConnection connection;

        public void onMessage(Message m)
        {
            if(connection.IsInternetavailable==true) //Null pointer is occuring here
            {
               //Do something with Message 
            } 
            else
            {
              //Do something with Message 
            }
         }
       }

Atest.java-Mockito Class

        Class ATest
        {

         @InjectMocks
         A resource;

         @Mock
            CheckConnection connection;

         @Test
            public void shouldProcessMessage() throws JMSException {
                // Arrange
                final String Type = "MessageType";
                final String Body = "MessageBody"

                final ActiveMQTextMessage message = new ActiveMQTextMessage();
                message.setStringProperty("messageType", Type);
                message.setText(Body);

                // Act
                this.resource.onMessage(message);  //This method fails i.e. it gives null pointer exception
            }
        }

1 个答案:

答案 0 :(得分:1)

首先:注释为InjectMocks而不是InjectMock s 缺失

第二:您需要使用此调用MockitoAnnotations.initMocks(this);来初始化模拟,这应该是您的设置方法或首次调用您的测试方法。

相关问题