使用Powermock在@Mock(模拟最终静态Hashtable)中的Nullpointer

时间:2016-03-17 18:41:00

标签: java junit testng spring-mybatis

我有一个应用程序(使用注释的Spring MVC 4 + Hibernate / JPA + MySQL + Maven集成示例),使用基于注释的配置将Spring与Hibernate集成。

我有这个控制器:

  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");

        }        
    }

但是我在这行中有一个java.lang.NullPointerException:

日期lastsmsSend = SMS_NOTIFICATION.get(deviceEvent.getDevice()。getKey());

2 个答案:

答案 0 :(得分:0)

你不能使用mockito注入静态和最终变量。删除它们或创建真实值而不是模型。

答案 1 :(得分:0)

正如已经提到的那样 - Mockito不能将静音注入静态场(我特别没有提到最终场,因为PowerMock删除了最终修改器)。

您可以使用以下方法绕过限制:

Whitebox.setInternalState(AndroidBackController.class, "SMS_NOTIFICATION", smsNnotification);