【问题标题】:Mockito - throws nullpointerException when mocking a serviceMockito - 模拟服务时抛出 nullpointerException
【发布时间】:2014-10-20 09:54:38
【问题描述】:

我是 Mockito 和一般测试类的新手。

我正在尝试为我的控制器编写一个测试类。当我运行测试时,我想模拟我的服务以返回 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”部分时)。进一步查看,我发现所有变量都正常,但我模拟的服务仍然为空。

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

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

【问题讨论】:

    标签: java unit-testing spring-mvc mockito


    【解决方案1】:

    你应该打电话 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)
    }
    

    【讨论】:

    • 谢谢,这确实是我所缺少的。
    • 谢谢,正是我需要的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多