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

寵の児 提交于 2019-12-01 23:16:25

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!