mercredi 6 juillet 2016

Inject/set object during Mock Spring Junit test

I want to test controller in my project. I have following classes (not important code is skipped):

Home Controller:

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

and the test class:

    @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", "123@test.pl").param("password", "Test1!").param("rememberMe", "true"))
                .andExpect(status().isFound()).andExpect(redirectedUrl("/home"));
        UserSummary user = userService.findByEmail("info@test.com");
        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"));
    }

The controller works well during the normal execution of web application. I use User Interceptor to set user inside of Session Preferences class, which has scope session and its visible to all views. When I wrote Unit test it gives me the null pointer, when it tries to access user id, as the user obviously is not set in sessionPreferences.

The question is, how to set object inside autowired class in Junit? I see that my user interceptor is not working during Junit test. I want to be able to do something like this in test class:

this.sessionPreferences.setUser(user);

in order to call this method without null pointer:

eventSuggestedService.getSuggestedPopularEventsV2(sessionPreferences.getUser().getUserId(), 10, new Date(), 1, 5)

Thanks for the help.

Aucun commentaire:

Enregistrer un commentaire