0
我想在我的項目中測試控制器。我有以下類(不是重要的代碼被跳過):模擬春季Junit測試中注入/設置對象
首頁控制器:
@Autowired
private SessionPreferences sessionPreferences;
//controller methods
private Pager<EventSuggestedAndPopular> discoverSuggested() {
return SecurityUtils.isUserLogged()
? eventSuggestedService.getSuggestedPopularEventsV2(sessionPreferences.getUser().getUserId(), 10, new Date(), 1, 5)
: eventSuggestedService.getSuggestedPopularEventsV2(321, 10, new Date(), 1, 5);
}
和測試類:
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
@Autowired
MockHttpServletRequest request;
@InjectMocks
private HomeController controller;
@Mock
private SessionPreferences sessionPreferences;
@Autowired
private UserService userService;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testIndexWithLoggedUser() throws Exception {
this.mockMvc.perform(get("/login").header("Referer", ""));
this.mockMvc.perform(post("/login").param("email", "[email protected]").param("password", "Test1!").param("rememberMe", "true"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/home"));
UserSummary user = userService.findByEmail("[email protected]");
this.sessionPreferences.setUser(user);
// when(sessionPreferences.getUser()).thenReturn(user); //I also used this, but it didn't work.
this.mockMvc.perform(get("/").param("lat", "0.0").param("lon", "0.0").accept(MediaType.TEXT_HTML)).andExpect(status().isOk())
.andExpect(view().name("home"));
this.mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()).andExpect(view().name("home"));
this.mockMvc.perform(get("/home/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()).andExpect(view().name("home"));
}
控制器Web應用程序的正常執行過程中效果很好。我使用User Interceptor在會話首選項類中設置用戶,該類具有作用域會話並且對所有視圖都可見。 當我寫單元測試它給我的空指針,當它試圖訪問用戶ID,因爲用戶顯然沒有在sessionPreferences中設置。
問題是,如何在Junit中設置autowired類中的對象?我看到我的用戶攔截器在Junit測試期間不工作。 我希望能夠做這樣的事在測試類:
this.sessionPreferences.setUser(user);
爲了調用這個方法沒有空指針:
eventSuggestedService.getSuggestedPopularEventsV2(sessionPreferences.getUser().getUserId(), 10, new Date(), 1, 5)
感謝您的幫助。