2014-10-20 90 views
1

我是新來的Mockito和一般的測試類。Mockito - 在嘲笑服務時拋出nullpointerException

我想爲我的控制器寫一個測試類。當我運行我的測試時,我想嘲笑我的服務返回一個Dto對象列表。但是當我這樣做時,我得到了錯誤。

我的代碼:

Controller類

@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測試(我所說的 「當」 的一部分) 。仔細觀察,我發現所有的變量都是oke,但我嘲笑的服務仍然爲空。

我忘了實例化一些東西,或者我只是完全錯誤的我如何做到這一點。

歡迎您提供任何幫助或指示。

回答

4

你應該叫 MockitoAnnotations.initMocks(這)在你的設置方法:

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

謝謝,這是我錯過了確實是。 – 2014-10-20 11:47:50

+0

謝謝,那是我需要的確切的東西。 – 2018-01-08 09:39:45