If the datasource is auto-configured, it can be excluded for tests by excluding the DataSourceAutoConfiguration
class. A line like below would need to be added to the test:
@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
Might also need to move the @EnableJpaAuditing
annotation, which I assume is causing the Error creating bean with name 'jpaAuditingHandler'
exception, to a separate @Configuration
class that can be conditionally skipped
package io.github.devatherock.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@Configuration
@EnableJpaAuditing
@ConditionalOnProperty(name = "jpa.enabled", matchIfMissing = true)
public class JpaConfig {
}
Now the custom JpaConfig
class can be disabled in the api spec generation test by setting jpa.enabled=false
@TestPropertySource(properties = "jpa.enabled=false")
A complete minimal test(written in Spock), that generates an api spec while excluding datasource configuration and disabling JPA auditing, is below:
package io.github.devatherock.controller
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.TestPropertySource
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import spock.lang.Specification
import java.nio.file.Files
import java.nio.file.Paths
@SpringBootTest
@TestPropertySource(properties = "jpa.enabled=false")
@AutoConfigureMockMvc
@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
class GenerateApiDocSpec extends Specification {
@Autowired
MockMvc mockMvc
@Autowired
ObjectMapper objectMapper
void 'test generate api doc'() {
setup:
Files.deleteIfExists(Paths.get('api-spec.json'))
when:
String apiSpec = mockMvc.perform(MockMvcRequestBuilders.get('/v3/api-docs'))
.andReturn().response.contentAsString
then:
def json = objectMapper.readValue(apiSpec, Map)
json['paths']['/hello']
cleanup:
new File('api-spec.json') << apiSpec
}
}
The complete application and tests can be found on github