我有一个spring引导应用程序,我最近将它从1.3.3.RELEASE升级到了1.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;
}我正在升级到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);
}
}然而,当我尝试上面的方法时,我在Mockito.when语句中得到了NPE。我是不是遗漏了什么?
我尝试使用MockBean而不是SpyBean,但仍然没有变化。我还尝试将spy语句移动到@Test方法,而不是@Before,仍然有相同的NPE。
发布于 2016-11-27 04:39:40
问题出在TestExecutionListeners注解上。在现有侦听器之外添加MockitoTestExecutionListener修复了模拟/间谍bean的注入。
https://stackoverflow.com/questions/40822777
复制相似问题