情况:
- 我在微服务中使用
Spring Cloud
和Spring Boot
,该微服务正在加载数据库配置信息以配置连接。 - 我创建了一个测试来使用
Swagger
获取其余接口(interface)作为文档。 - 我想禁用加载数据库配置,因为没有必要。
代码如下:
@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());
}
}
如何在不加载数据库配置的情况下运行测试? 这可能吗?
最佳答案
可以选择仅使用普通 Spring 功能来伪造 Spring bean。您需要为其使用 @Primary
、@Profile
和 @ActiveProfiles
注释。
I wrote a blog post on the topic.
您可以使用内存数据库(例如 H2)来替换真实数据源。像这样的:
@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();
}
}
关于java - 如何在 Spring Boot 中模拟数据库连接以进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35707469/