我有一个spring boot应用程序,我最近从v1.3.3.RELEASE升级到v1.4.2.RELEASE。
对于我在v1.3.3中的集成测试,我有一个我能够成功窥探的bean。我正在使用个人资料test
运行我的测试,而passwordEncoder
下方已激活而不是应用程序。
@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;
}
@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;
}
我正在升级到v1.4.2.RELEASE,并希望使用spyBean批注来模拟单个方法而不依赖于配置文件。
我对我的测试方法进行了以下更改以试用它 -
@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);
}
}
然而,当我尝试上述内容时,我会在@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);
}
}
声明中获得NPE。有什么我想念的吗?
我尝试使用MockBean而不是SpyBean,但仍然没有变化。我还尝试将间谍语句移到方法而不是
Mockito.when
,并且仍然具有相同的NPE。
答案 0 :(得分:0)
问题在于TestExecutionListeners
注释。除现有侦听器外,添加MockitoTestExecutionListener
修复了mock / spy bean的注入。