简体   繁体   中英

spring-boot-test spyBean annotation not injecting dependency

I have a spring boot application which I have recently upgraded from v1.3.3.RELEASE to v1.4.2.RELEASE.

For my integration tests in v1.3.3, I have a bean which I was able to successfully spy. I was running my tests with the profile test and below passwordEncoder was activated instead of the application's.

 @Bean @Profile({"test"}) PasswordEncoder passwordEncoder(){ PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(ApplicationConstants.CRYPT_LOG_ROUNDS); final String pwdHash = "$$CONST_HASH$$"; PasswordEncoder peSpy = spy(passwordEncoder); Mockito.when(peSpy.encode("TEST_USER_CRED")).thenReturn(pwdHash); return peSpy; } 

I am doing a upgrade to v1.4.2.RELEASE and would like to use the spyBean annotation to mock a single method and not depend on profiles.

I have made following changes to my test method to try it out -

 @RunWith(SpringRunner.class) @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,DirtiesContextTestExecutionListener.class,DbUnitTestExecutionListener.class }) @DbUnitConfiguration(dataSetLoader = ReplacementDataSetLoader.class) @SpringBootTest(classes = Application.class,webEnvironment=WebEnvironment.RANDOM_PORT) public class MockTests { @SpyBean PasswordEncoder passwordEncoder; private MockMvc mockMvc; @Before public void setup() throws Exception { this.mockMvc = webAppContextSetup(webApplicationContext) .apply(springSecurity()) .build(); final String pwdHash = "$$CONST_HASH$$"; Mockito.when(peSpy.encode("TEST_USER_CRED")).thenReturn(pwdHash); } } 

However, when I try the above, I get NPE at Mockito.when statement. Is there anything I am missing?

I tried to use MockBean instead of SpyBean but still has no change. I also tried to move the spy statements to @Test methods instead of @Before and still have same NPE.

The issue was with the TestExecutionListeners annotation. Adding MockitoTestExecutionListener in addition to existing listeners fixed the injection of mock/spy beans.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM