2016-02-29 52 views
9

現狀:如何在Spring Boot中模擬db連接以進行測試?

  1. 我在微服務使用Spring CloudSpring Boot,即微服務加載的是DB的配置信息來配置的連接。
  2. 我創建了一個測試,使用Swagger獲取其餘接口的文檔。
  3. 我想禁用加載數據庫配置,因爲沒有必要。

下面是代碼:

@WebAppConfiguration 
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {Application.class, Swagger2MarkupTest.class}, loader = SpringApplicationContextLoader.class) 
@ActiveProfiles("test") 

public class Swagger2MarkupTest { 

    @Autowired 
    private WebApplicationContext context; 

    private MockMvc mockMvc; 

    @Autowired 
    protected Environment env; 

    @Before 
    public void setUp() { 
     this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); 
    } 

    @Test 
    public void convertSwaggerToAsciiDoc() throws Exception { 
     this.mockMvc.perform(get("/v2/api-docs").accept(MediaType.APPLICATION_JSON)) 
       .andDo(Swagger2MarkupResultHandler.outputDirectory("target/docs/asciidoc/generated") 
         .withExamples("target/docs/asciidoc/generated/exampless").build()) 
       .andExpect(status().isOk()); 
    } 
} 

如何,我可以運行,而無需加載數據庫配置的考驗嗎? 這可能嗎?

+1

模擬你的服務層。就那麼簡單。 –

回答

10

有一個選項可以用純Spring的特性來僞造Spring bean。您需要爲其使用@Primary@Profile@ActiveProfiles註釋。

I wrote a blog post on the topic.

可以在存儲器使用DB(例如H 2),以取代實際數據源。類似這樣的:

@Configuration 
public class TestingDataSourceConfig { 

    @Bean 
    @Primary 
    public DataSource dataSource() { 
     return new EmbeddedDatabaseBuilder() 
      .generateUniqueName(true) 
      .setType(H2) 
      .setScriptEncoding("UTF-8") 
      .ignoreFailedDrops(true) 
      .addScript("schema.sql") 
      .addScripts("user_data.sql", "country_data.sql") 
      .build(); 
    } 
} 
相關問題