request scoped beans in spring testing

后端 未结 8 902
自闭症患者
自闭症患者 2020-11-30 00:54

I would like to make use of request scoped beans in my app. I use JUnit4 for testing. If I try to create one in a test like this:

@RunWith(SpringJUnit4Clas         


        
8条回答
  •  一整个雨季
    2020-11-30 01:13

    A solution, tested with Spring 4, for when you require request-scoped beans but aren't making any requests via MockMVC, etc.

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(/* ... */)
    public class Tests {
    
        @Autowired
        private GenericApplicationContext context;
    
        @Before
        public void defineRequestScope() {
            context.getBeanFactory().registerScope(
                WebApplicationContext.SCOPE_REQUEST, new RequestScope());
            RequestContextHolder.setRequestAttributes(
                new ServletRequestAttributes(new MockHttpServletRequest()));
        }
    
        // ...
    

提交回复
热议问题