我是powermockito单元测试的新手,目前我正在尝试测试一个调用java.util.Timer.scheduleAtFixedRate
的方法。我试着运行测试,但失败了,在对象调用方法的那一行显示了NullPointerException
,我认为这里的对象不是null。这是我的代码,我总结了可能导致问题的部分。
每日提醒测试.java
@RunWith(PowerMockRunner.class)
@PrepareForTest(DailyReminder.class)
public class DailyReminderTest {
@InjectMocks
DailyReminder dailyReminder;
@Mock
User user;
@Mock
Timer mockTimer;
@Mock
TimerTask mockTask;
@BeforeEach
public void setUp() {
TimerTask task = new MyTask(user);
mockTask = mock(task.getClass());
dailyReminder = new DailyReminder() {
@Override
public Timer createTimer() {
return mockTimer;
}
@Override
public TimerTask createTask() {
return mockTask;
}
};
}
@Test
void testRemind() throws Exception {
dailyReminder.remind(); // here is the line where NullPointerException occured
verify(mockTimer).scheduleAtFixedRate(eq(mockTask), any(Date.class), anyLong());
}
}
每日提醒.java
public class DailyReminder {
private Timer timer;
private TimerTask task;
private User user;
private Date dateStart;
private final Duration fixedDuration = Duration.of(1, ChronoUnit.DAYS);
// some constructor here...
public void remind() {
timer = createTimer();
task = createTask();
timer.scheduleAtFixedRate(task, dateStart, fixedDuration.toMillis());
}
public Timer createTimer() {
return new Timer();
}
public TimerTask createTask() {
return new MyTask(user);
}
}
我也尝试过assertNull(dailyReminder)
,但是堆栈跟踪显示
org.opentest4j.AssertionFailedError: expected: <null> but was: <Daily Reminder>
奇怪的是dailyReminder没有空。对此有什么解释吗?
如果使用PowerMockRunner
,则必须调用MockitoAnnotations.initMocks()
才能初始化使用注释创建的mock。当前mockTimer
为空,从而为您提供NPE。您可以像对待其他mock那样在beforeEach
中初始化它,也可以调用initMocks()
来修复此问题。