簡體   English   中英

為測試覆蓋基於Java的Spring Context配置

[英]Overwrite Java based Spring Context Configuration for Tests

是否有可能從Spring配置中替換單個bean或值進行一個或多個集成測試?

就我而言,我有配置

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"foo.bar"})
public class MyIntegrationTestConfig {
    // everything done by component scan
}

哪個用於我的集成測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyIntegrationTestConfig.class, loader = SpringApplicationContextLoader.class)
public class MyIntegrationTest {
    // do the tests
}

現在我想要進行第二組集成測試,其中我用一個不同的bean替換一個bean。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyIntegrationTestConfig.class, loader = SpringApplicationContextLoader.class)
public class MySpecialIntegrationTest {
    // influence the context configuration such that a bean different from the primary is loaded

    // do the tests using the 'overwritten' bean
}

實現這一目標的最簡單方法是什么?

Spring測試框架能夠理解擴展配置。 這意味着您只需要從MyIntegrationTest擴展MySpecialIntegrationTest

@ContextConfiguration(classes = MySpecialIntegrationTestConfig.class, loader = SpringApplicationContextLoader.class)
public class MySpecialIntegrationTest extends MyIntegrationTest {

  @Configuration
  public static class MySpecialIntegrationTestConfig {
    @Bean
    public MyBean theBean() {}
  }

}

並創建必要的Java Config類並將其提供給@ContextConfiguration Spring將加載基礎並將其擴展為您專門用於擴展測試用例的那個。

有關進一步的討論,請參閱官方文檔

暫無
暫無

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

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