I inject the HttpSession into my controller with @Autowired:
@RestController
public class MyController {
@Autowired
private HttpSession httpSession;
@GetMapping("hello")
public String getHello() {
return "hello " + httpSession.getId();
}
}
How can I mock the session in a @WebMvcTest annotated test?
@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private HttpSession session;
@Test
public void testGetHello() throws Exception {
when(session.getId()).thenReturn("sessionId");
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("hello sessionId"));
}
}
This solution throws exception: No qualifying bean of type 'javax.servlet.http.HttpSession' available