I'm trying to test session scoped bean in Spring-boot but i've encountered problem. I've created two MockHttpSession and try to inject them into controller method, which then will add to them scoped bean. If i run application those beans are different in each scope, but when i try to test it, the object is the same. Here is my test:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class ObserverSessionScopedIT {
@Autowired
private
ObserverController controller;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void sessionScope() throws Exception {
MockHttpSession sessionFirst = new MockHttpSession();
MockHttpSession sessionSecond = new MockHttpSession();
sessionFirst.changeSessionId();
sessionSecond.changeSessionId();
controller.startObserving(temporaryFolder.getRoot().getAbsolutePath(), sessionFirst);
controller.startObserving(temporaryFolder.getRoot().getAbsolutePath(), sessionSecond);
Subscriptions subscriptionsFirst = (Subscriptions) sessionFirst.getAttribute("Subscriptions");
Subscriptions subscriptionsSecond = (Subscriptions) sessionSecond.getAttribute("Subscriptions");
Assertions.assertThat(subscriptionsFirst).isNotSameAs(subscriptionsSecond);
}
and here is how i menage it in controller:
private static final String SUBSCRIPTION = "Subscriptions";
(...)
@Autowired
private Subscriptions subscriptions;
@CrossOrigin
@RequestMapping(path = "/start", method = RequestMethod.POST)
@ResponseBody ResponseEntity<String> startObserving(@RequestBody String path, HttpSession httpSession) throws IOException {
(...)
httpSession.setAttribute(SUBSCRIPTION, subscriptions);
(...)
}
and this is definition of Subscriptions object:
@Service
@SessionScope
public class Subscriptions implements AutoCloseable{
Why i have two different objects while application works, but in test it's the same reference? I think it might be connected to context in test, but can i run tests with main application context?
Aucun commentaire:
Enregistrer un commentaire