gpt4 book ai didi

java - spring-boot-test spyBean 注释未注入(inject)依赖项

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:55 26 4
gpt4 key购买 nike

我有一个 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;
}

我正在升级到 v1.4.2.RELEASE,并希望使用 spy Bean注释来模拟单个方法而不依赖于配置文件。

我对我的测试方法进行了以下更改来尝试 -

@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。

最佳答案

问题出在 TestExecutionListeners 注释上。除了现有监听器之外,添加 MockitoTestExecutionListener 修复了模拟/ spy bean 的注入(inject)。

关于java - spring-boot-test spyBean 注释未注入(inject)依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40822777/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com