我正在使用spring啓動項目,我們剛剛升級到版本1.4.0.RELEASE。作爲版本升級的一部分,我們已經開始在抽象集成測試類中使用@SpringBootTest批註。在閱讀the documentation後,聽起來好像我們應該能夠在特定測試期間使用嵌套的@ TestConfiguration註釋的配置類來覆蓋bean定義。這不適合我們,而是我們試圖覆蓋的非測試bean仍在使用中。有趣的是,似乎模擬測試bean和生產bean的用法實際上是在同一個測試中交織在一起的,就像兩個bean在應用程序上下文中並排存在一樣。此外,它看起來像集成測試以某種方式運行的順序會影響此行爲。我想知道這是我們配置錯誤還是有其他事情發生。嵌套配置不能按預期工作
編輯:
的抽象類,集成測試,從外觀繼承這樣的:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles({"local", "test"})
public abstract class BaseIntegrationTest {
@Value("${local.server.port}")
protected int port;
}
,我們看到了奇怪的行爲看起來像這樣的集成測試:
public class WebhookProcessorIT extends BaseIntegrationTest {
@TestConfiguration
public static class Config {
@Bean
@Primary
public WebhookTask webhookTask() {
return mock(WebhookTask.class);
}
}
// sometimes the mock above is used and sometimes
// the actual production bean is used
@Autowired
private WebhookTask task;
@Before
public void setup() {
when(task.process(any())).thenReturn(true);
}
// tests ...
}
這就是根應用程序上下文類的樣子:
@EnableAutoConfiguration(exclude = ErrorMvcAutoConfiguration.class)
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
final SpringApplication app = new SpringApplication(Application.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
}
編輯:
我一直在使用@MockBean
,像這樣也試過:
public class WebhookProcessorIT extends BaseIntegrationTest {
@MockBean
private WebhookTask task;
,但我得到了相同的結果測試運行時。我可以看到春天正試圖在我的測試設置中查看日誌覆蓋生產豆與我所提供的模擬:
build 15-Sep-2016 09:09:24 2016-09-15 09:09:24 [34mINFO [0;39m [36m[DefaultListableBeanFactory][0;39m (main) Overriding bean definition for bean 'productionWebhookTask' with a different definition
然而,當涉及到測試的執行,我仍然可以看到生產豆使用:
build 15-Sep-2016 09:09:29 2016-09-15 09:09:29 [39mDEBUG[0;39m [36m[WebhookSupplier][0;39m (WebhookProcessor) Received webhook with ID '1234' from queue.
build 15-Sep-2016 09:09:30 2016-09-15 09:09:30 [39mDEBUG[0;39m [36m[WebhookSupplier][0;39m (WebhookProcessor) Received webhook with ID '5678' from queue.
build 15-Sep-2016 09:09:30 2016-09-15 09:09:30 [39mDEBUG[0;39m [36m[ProductionWebhookTask][0;39m (WebhookProcessor) Received webhook with ID '1234' for processing // production webhook task bean still being used for webhook '1234'
build 15-Sep-2016 09:09:30 2016-09-15 09:09:30 [39mDEBUG[0;39m [36m[WebhookSupplier][0;39m (WebhookProcessor) Deleting webhook with id '5678' from queue. // mock bean causes production logic to be skipped and we just delete webhook '5678'
// More logs from production webhook task operating on webhook with id '1234' and causing the test to fail
你的意思是偶爾有真正的豆運行,而不是嘲笑一個還是什麼? –
您可以分享您的測試課程,以便我們可以更多地瞭解您的具體設置? –
@ShadyRagab好像是這樣。 – enbdk