jeudi 30 mai 2019

Problems when accessing Session attributes in Spring Test

I am developing a Spring webservice and I need to read data & set them as a Session attribute in an interceptor. Everything works fine when I test the endpoints using an external client. However, I get a NullPointerException when I try the code below:

@RunWith(SpringRunner.class)
@WebMvcTest(AccountController.class)
public class AccountControllerTest {

private MockMvc mockMvc;

@InjectMocks
private AccountController accountController;

@MockBean
private IncomingInterceptor incomingInterceptor;

@MockBean
private AccountService accountService;

@MockBean
private FileStoreService fileStoreService;

@MockBean
private HttpServletRequest request;

private Gson gson;

@Before
public void setup() {
    gson = new Gson();
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).addInterceptors(incomingInterceptor).build();
}

@Test
public void testAddAccount() throws Exception {
    JsonObject root = new JsonObject();
    root.add("body", gson.toJsonTree(account));

    Mockito.when(accountController.addAccount()).thenReturn(new ResponseEntity<>(1L, HttpStatus.OK));

    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/account/register")
            .content(root.toString())
            .characterEncoding("utf-8")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();

    String contentAsString = mvcResult.getResponse().getContentAsString();
    System.out.println("contentAsString = " + contentAsString);
}
}

Everyting works as expected when the attributes are set in the interceptor but when I try to access them in AccountController an exception is thrown.

The code to access attributes:

 JsonObject body = (JsonObject) request.getSession().getAttribute("body");           

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire