为什么会话范围bean对于测试中的不同模拟会话是相同的

时间:2016-11-17 14:10:11

标签: java spring session testing spring-boot

我试图在Spring-boot中测试会话范围的bean,但我遇到了问题。 我创建了两个MockHttpSession并尝试将它们注入到控制器方法中,然后将其添加到scoped bean中。如果我运行应用程序,那些bean在每个范围内都是不同的,但是当我尝试测试它时,对象是相同的。这是我的测试:

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

}

以下是我如何在控制器中管理它:

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);
     (...)
    }

这是Subscriptions对象的定义:

@Service
@SessionScope
public class Subscriptions implements AutoCloseable{

为什么我在应用程序工作时有两个不同的对象,但在测试中它是相同的参考?我认为它可能与测试中的上下文相关联,但是我可以使用主应用程序上下文运行测试吗?

0 个答案:

没有答案