简体   繁体   中英

Mockito - throws nullpointerException when mocking a service

I'm new to Mockito and testclasses in general.

I'm trying to write a test class for my controller. When I run my test I want to mock my service to return a list of Dto objects. But when I do this I get the error.

my code:

Controller class

@Controller
public class CalendarController {

@Resource
private CalendarService calendarService;

@RequestMapping(method = RequestMethod.GET,value = RequestMappings.CALENDAR, produces = ContentType.APPLICATION_JSON)
public ResponseEntity<List<CalendarDto>> getCalendarMonthInfo(@PathVariable final String userId, @PathVariable final String year)
{
    List<CalendarDto> result = new ArrayList<CalendarDto>();
    result = calendarService.getMonthInfo(userId,Integer.parseInt(year));

    return new ResponseEntity<>(result, HttpStatus.OK);
}

Test class

public class CalendarControllerTest extends BaseControllerIT {

    List<CalendarDto> calendarDto;
    CalendarDto test1 , test2;
    String userId = "20";
    String year = "2014";

    @Mock
    public CalendarService calendarService;

    @Before
    public void setUp() throws Exception {
        calendarDto = new ArrayList<CalendarDto>();
        test1 = new CalendarDto();
        test1.setStatus(TimesheetStatusEnum.APPROVED);
        test1.setMonth(1);
        test2 = new CalendarDto();
        test2.setMonth(2);
        test2.setStatus(TimesheetStatusEnum.REJECTED);
        calendarDto.add(test1);
        calendarDto.add(test2);
    }

    @Test
    public void testGet_success() throws Exception {
        when(calendarService.getMonthInfo(userId,Integer.parseInt(year))).thenReturn(calendarDto);
        performGet(UrlHelper.getGetCalendarMonthInfo(userId,year)).andExpect(MockMvcResultMatchers.status().isOk());
    }
}

I get a nullPointerException in the test (When I call the "when" part). Looking further into it I saw that all the variables are oke but the service that I mock remains null.

Am i forgetting to instantiate something or am I just completely wrong in how I'm doing this.

Any help or pointers you can give are welcome.

You should call MockitoAnnotations.initMocks(this) in your setup method:

  @Before
public void setUp() throws Exception {
    calendarDto = new ArrayList<CalendarDto>();
    test1 = new CalendarDto();
    test1.setStatus(TimesheetStatusEnum.APPROVED);
    test1.setMonth(1);
    test2 = new CalendarDto();
    test2.setMonth(2);
    test2.setStatus(TimesheetStatusEnum.REJECTED);
    calendarDto.add(test1);
    calendarDto.add(test2);

    MockitoAnnotations.initMocks(this)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM