nullpointerexception

ars1skjm  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(464)

模拟gettimezone方法时获取空指针异常。defaultsystemtimezone是从属性文件填充的。

SummaryServiceTest.java: 

@RunWith(PowerMockRunner.class)
@PrepareForTest({Calendar.class, TimeZone.class})
@ExtendWith(SpringExtension.class)
class SummaryServiceTest{

    @Mock
    BookingRepository bookingRepository;

    @InjectMocks
    private SummaryService summaryService;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void getBookingRejections() throws Exception {
        TimeZone timezoneObj = TimeZone.getTimeZone("America/Cambridge_Bay");
        PowerMockito.mockStatic(TimeZone.class);
        Mockito.when(TimeZone.getTimeZone(eq("America/Cambridge_Bay"))).thenReturn(timezoneObj);
        Calendar calendar1 = Calendar.getInstance(TimeZone.getDefault(), Locale.US);
        Calendar ac = PowerMockito.mock(Calendar.class);
        PowerMockito.doReturn(calendar1).when(ac , "getInstance");
        Boolean bookingRejectionsByWeekForCarrierList = summaryService.getBookingRejections();
    }
}

SummaryService.java:

@Service
public class SummaryService {

    @Autowired
    private BookingRepository bookingRepository;

    @Value("${timezone.default}")
    private String defaultSystemTimezone;

    public Boolean getBookingRejections() {
            Calendar calendarFirstDayOfWeek = Calendar.getInstance(TimeZone.getTimeZone(defaultSystemTimezone), Locale.US);
            return true;
        }
    }

application.properties:

    timezone.default=America/Cambridge_Bay

正在获取以下异常:

java.lang.NullPointerException
    at java.util.TimeZone.parseCustomTimeZone(TimeZone.java:783)
    at java.util.TimeZone.getTimeZone(TimeZone.java:562)
    at java.util.TimeZone.getTimeZone(TimeZone.java:516)
    at com.booking.service.SummaryServiceTest.getBookingRejections(SummayServiceTest.java:)

即使时区被嘲笑,也不能精确地解决问题。这里尝试获取日历对象。

pxyaymoc

pxyaymoc1#

通过为summaryservice的defaultsystemtimezone变量添加setter解决了此问题。并在测试方法中设置var值。

SummaryService.java:

@Service
public class SummaryService {

    @Autowired
    private BookingRepository bookingRepository;

    @Setter
    @Value("${timezone.default}")
    private String defaultSystemTimezone;

    public Boolean getBookingRejections() {
            Calendar calendarFirstDayOfWeek = Calendar.getInstance(TimeZone.getTimeZone(defaultSystemTimezone), Locale.US);
            return true;
        }
    }

    @Test
        public void getBookingRejections() throws Exception {
            summaryService.setDefaultSystemTimezone("America/Cambridge_Bay");
            //execute test
        }

相关问题