Tom
Tom

Reputation: 4151

@Autowire in unit tests does not seem to work

I have a unit test setup using Mockito and Spring 4. My test looks like this:

@ContextConfiguration(classes = {
        MyTestConfig.class,
        SecurityConfig.class,
        OAuth2Config.class
})
@RunWith(MockitoJUnitRunner.class)
public class ControllerAccessTests {

    private MockMvc mockMvc;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    @Mock
    private CreditCardPaymentService creditCardPaymentService;
    @InjectMocks
    private CreditCardRestController creditCardRestController;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders
                .standaloneSetup(creditCardRestController)
                .apply(springSecurity(springSecurityFilterChain))
                .build();
        when(creditCardPaymentService.doPreAuthPayment(any())).thenReturn(null);
    }

    @Test
    //.... some unit tests

With a configuration file that looks like this:

@Configuration
public class MyTestConfig {

    @Bean
    public FilterChainProxy springSecurityFilterChain(){
        AntPathRequestMatcher matcher = new AntPathRequestMatcher("/**");
        DefaultSecurityFilterChain chain = new DefaultSecurityFilterChain(matcher);
        return new FilterChainProxy(chain);
    }

}

When I start the unit test springSecurityFilterChain is null, so it seems the configuration file MyTestConfig does not seem to get loaded. Any ideas?

Cheers Tom

Upvotes: 1

Views: 1174

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26502

If you want to use mockito annotations and spring injection then:

1) Use @RunWith(SpringJUnit4ClassRunner.class)

2) Create an init method:

@Before
public void init(){
 MockitoAnnotations.initMocks(this);
}

Upvotes: 6

Related Questions