![](/img/trans.png)
[英]NullPointerException in Mockito when mocking method with primitive argument
[英]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.