【问题标题】:spring-boot-test spyBean annotation not injecting dependencyspring-boot-test spyBean 注解不注入依赖
【发布时间】:2017-04-10 21:42:51
【问题描述】:

我有一个 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,并希望使用 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,但仍然没有任何变化。我还尝试将间谍语句移动到 @Test 方法而不是 @Before 并且仍然具有相同的 NPE。

【问题讨论】:

    标签: java unit-testing junit spring-boot spring-test


    【解决方案1】:

    问题出在TestExecutionListeners 注释上。在现有侦听器之外添加 MockitoTestExecutionListener 修复了模拟/间谍 bean 的注入。

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 1970-01-01
      • 2011-11-06
      • 2021-12-28
      • 2016-06-05
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多