繁体   English   中英

Mockito-模拟服务时抛出nullpointerException

[英]Mockito - throws nullpointerException when mocking a service

我是Mockito和testclass的新手。

我正在尝试为我的控制器编写一个测试类。 当我运行测试时,我想模拟我的服务以返回Dto对象的列表。 但是当我这样做时,我得到了错误。

我的代码:

控制器类

@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);
}

测试班

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());
    }
}

我在测试中得到一个nullPointerException(当我调用“ when”部分时)。 进一步研究它,我发现所有变量都是oke,但是我嘲笑的服务仍然为空。

我是忘记实例化某些东西还是我在执行此操作时完全错了。

欢迎您提供任何帮助或指示。

您应该在设置方法中调用MockitoAnnotations.initMocks(this):

  @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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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