Reputation: 5
i have code like below
ScheExeService.ScheduleId scheduleID = ScheExeService.getOneTimeScheduleId(nl.getCompany(), workItem.getId());
ScheExeService.Schedule schedule = ScheExeService.loadSchedule(nl, scheduleID.getId());
Calendar cal = Calendar.getInstance(java.util.TimeZone.getTimeZone(nl.getTimeZone()));
cal.setTime(schedule.attributes.startDate.toDate());
AND i am trying to mock "schedule.attributes.startDate.toDate()"
and ScheExeService look like below
public class ScheExeService implements blah
{
public final static class Schedule {
public final ScheduleId id;
public final ScheduleAttributes attributes;
public final String callableClassName;
public final long itemId;
public Schedule(ScheduleId id, ScheduleAttributes attributes, String callableClassName, long itemId)
{
this.id = id;
this.attributes = attributes;
this.callableClassName = callableClassName;
this.itemId = itemId;
}
}
public final static class ScheduleAttributes {
public final @Nullable LocalDate startDate;
public final @Nullable LocalTime startTime;
public final @Nullable LocalDate endDate;
public final @Nullable LocalTime endTime;
Method code
}
}
and i tried
doNothing().doThrow(new RuntimeException()).when(mockedCalenderObject).setTime(null);
but i am keep getting NPE.
how i can avoid schedule.attributes.startDate.todate() call..?
Upvotes: 0
Views: 602
Reputation: 95704
It's a good idea not to mock data/value objects like List and String, including Joda objects like LocalDate and LocalTime and your data objects like Schedule and ScheduleAttributes. This is mostly because, unless the instances are hard to create, you can just create instances in your test and have the getters and setters behave as expected.
See also: "Test smell: Everything is mocked"
Based on your code, I'd very much suggest mocking loadSchedule
(which may require refactoring ScheExeService away from static methods, refactoring the second half of your system under test to accept an arbitrary Schedule, or using PowerMock) and creating your test Schedule using real calls.
public void yourMethod(NL nl, WorkItem workItem) {
ScheExeService.ScheduleId scheduleID = ScheExeService.getOneTimeScheduleId(nl.getCompany(), workItem.getId());
ScheExeService.Schedule schedule = ScheExeService.loadSchedule(nl, scheduleID.getId());
processSchedule(schedule);
}
/**
* Processes schedule for yourMethod. Exposed for testing: Create as many
* arbitrary Schedules as you want and pass them in to test this thoroughly.
*/
void processSchedule(Schedule schedule) {
Calendar cal = Calendar.getInstance(java.util.TimeZone.getTimeZone(nl.getTimeZone()));
cal.setTime(schedule.attributes.startDate.toDate());
// ...
}
Upvotes: 1