-1

I have an application (Spring MVC 4 + Hibernate/JPA + MySQL + Maven integration example using annotations), integrating Spring with Hibernate using annotation based configuration.

I have this controller:

  public class AndroidBackController {

        protected static final Logger LOGGER = LoggerFactory.getLogger(AndroidBackController.class);

        private static final Hashtable<String, Date> SMS_NOTIFICATION = new Hashtable<String, Date>();

@RequestMapping(value = { "/sigfoxCallBack" }, method = RequestMethod.GET)
    public String performAndroidCallBack(@RequestParam Map<String, String> allRequestParams) throws ClientProtocolException, IOException {

 Date lastsmsSend = SMS_NOTIFICATION.get(deviceEvent.getDevice().getKey());

    ..
    }

and this Test:



  public class AndroidBackControllerTest {

        @InjectMocks
        AndroidBackController androidCallBackController;

        @Mock
        DeviceService deviceService;

        @Mock
        DeviceEventService deviceEventService;

        @Mock
        Hashtable<String, Date> SMS_NOTIFICATION = new Hashtable<String, Date>();


        @Mock
        Map<String, String> allRequestParams;

        @BeforeClass
        public void setUp(){
            MockitoAnnotations.initMocks(this);
        }

        @Test
        public void androidCallBack() throws ClientProtocolException, IOException {

             PowerMockito.mockStatic(Hashtable.class);

            Device device = new Device();
            DeviceType deviceType = new DeviceType();
            deviceType.setType("SMARTEVERYTHING_KIT");
            device.setDeviceType(deviceType);

            when(allRequestParams.get("devideId")).thenReturn("E506");
            when(allRequestParams.get("rssi")).thenReturn("155.55");
            when(SMS_NOTIFICATION.get("E506")).thenReturn(new Date());


            when(deviceService.findByKey("E506")).thenReturn(device);



            Assert.assertEquals(androidCallBackController.performAndroidCallBack(allRequestParams), "alldevices");

        }        
    }

but I have a java.lang.NullPointerException in this line:

Date lastsmsSend = SMS_NOTIFICATION.get(deviceEvent.getDevice().getKey());

Rufi
  • 2,529
  • 1
  • 20
  • 41
  • Mockito can't inject static fields, and can't inject final fields either. And SMS_NOTIFICATION is both. – JB Nizet Mar 17 '16 at 18:45

2 Answers2

0

You cannot inject on static and final variables using mockito. Either remove those or create a real value instead of a mockup.

Stephen Carman
  • 999
  • 7
  • 25
0

As has already been mentioned - Mockito cannot inject mocks to static fields( I special doesn't mentioned about final field, because PowerMock remove final modifier).

You may bypass limitation by using:

Whitebox.setInternalState(AndroidBackController.class, "SMS_NOTIFICATION", smsNnotification);
Artur Zagretdinov
  • 2,034
  • 13
  • 22