2016-02-29 50 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(); 
    } 
} 
相关问题