簡體   English   中英

測試時如何以不同的方式配置 Spring @Component

[英]How to configure a Spring @Component differently when testing

我正在嘗試通過編寫一個應用程序來學習 Spring,該應用程序通過 2 個服務類從 2 個 LDAP 源查詢信息。

我有一個 ActiveDirectory 源:

@Component
public class AdLdapService implements LdapService {
    @Override
    public Optional<LdapMember> getUserById(String accountName) throws Exception {
    }
}

這是使用配置的

@Configuration
public class AdLdapConfiguration {

    @Autowired
    Environment env;

    @Bean("ad-context")
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(env.getRequiredProperty("ldap.ad.url"));
        contextSource.setBase(env.getRequiredProperty("ldap.ad.base"));
        contextSource.setUserDn(env.getRequiredProperty("ldap.ad.user"));
        contextSource.setPassword(env.getRequiredProperty("ldap.ad.password"));
        return contextSource;
    }

    @Bean("ad-template")
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSource());
    }
}

我還有第二對類用於訪問不同的 LDAP 源。 這一切正常。

現在我想添加一些單元測試來測試這 2 個服務,而不是使用實時 LDAP,我認為最好動態創建一個小型嵌入式 LDAP 並對其進行測試。 這是我被卡住的地方。

我想創建 2 個單獨的 LDAP 並從 2 個 LDIF 文件中填充它們。 我的 2 個LdapService實現應該鏈接到相關的嵌入式 LDAP。

我的 Spring 知識仍然非常有限,我不知道設置它的優雅方式。

您可以從一個測試開始,該測試將使用您選擇的配置加載應用程序上下文:

@RunWith(SpringRunner.class)
@ContextConfiguration(...<YOUR_CONFIG_GOES_HERE>)
public void MySampleLdapTest {

    @Autowired
    public LdapTemplate testTemplate;

    @Test
    public void testLdap() {
      testTemplate.doWhateverYouNeedAndVerifyTheResult();
    }
}

現在,如果您需要在內存中運行 LDAP 服務,那肯定是一個集成測試。 您可以執行以下操作之一:

  1. 使用 TestContainers 框架啟動 LDAP 服務 Docker 映像並與之交互。
  2. 找到一些 LDAP 服務器的內存實現並與測試集成。
  3. 如果要模擬與 LdapService 交互的 bean,但仍希望使用一堆 bean 加載應用程序上下文,請使用@MockBean注釋。 這是一個特殊的注釋,它改變了應用程序上下文:如果有一個這種類型的 bean - 它會在應用程序上下文中放置一個模擬(用 mockito 創建的常規模擬),如果根本沒有 bean - 它會創建模擬並將其添加到應用程序上下文中。

最后但並非最不重要的是,所有這些測試都比常規的 mockito 樣式單元測試慢得多。 一般來說,spring 測試是一個很好的工具,但它用於集成測試,而不是用於單元測試。 如果您可以使用 mockito 進行完全沒有 spring 的單元測試 - 它可能是一個更好的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM