Spring: cannot inject a mock into class annotated with the @Aspect annotation

前端 未结 1 538
抹茶落季
抹茶落季 2021-01-20 04:01

I created a Before advice using AspectJ:

package test.accesscontrol.permissionchecker;

import test.accesscontrol.database.SessionExpiredException;
import te         


        
相关标签:
1条回答
  • 2021-01-20 04:18

    The issue here is that your Mock instances and the ValidSessionChecker are not Spring beans and so are not being wired into the ValidSessionChecker managed by Spring. To make the mocks Spring beans instead probably a better approach will be to create another bean definition file which extends the beans defined in the base configuration file and adds mocks:

    test-config.xml:

    <beans...>
        <import resource="base-springmvc-config.xml"/>
        <beans:bean name="usersDatabaseAccessProvider" factory-method="mock"    class="org.mockito.Mockito">
        <beans:constructor-arg value="..UsersDatabaseAccessProvider"></beans:constructor-arg>
    </beans:bean>
    

    And then in your test inject behavior into the mock:

    public class AccessControlControllerTestsWithInjectedMocks {
    
        @Autowired
        private org.springframework.web.context.WebApplicationContext wac;
    
        private MockMvc mockMvc;
    
        @Autowired
        UsersDatabaseAccessProvider usersDatabaseAccessProvider;
    
        @Autowired
        ValidSessionChecker validSessionChecker;
    
        ....
    
        @Before
        public void before() throws Throwable {
            //given
            MockitoAnnotations.initMocks(this);
    
            when(usersDatabaseAccessProvider.sessionNotExpired("123456")).thenReturn(Boolean.FALSE);
    
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
        }
    

    This should cleanly work.

    0 讨论(0)
提交回复
热议问题