I'm trying to test some services in Micronaut which do not need a datasource connection but if there is a datasource configured in the application.yml
then running a @MicronautTest
connects to the database.
application.yml
# ...
datasources:
default:
url:
username:
password:
# ...
a dummy controller which returns Okay 200:
@Controller("/api/heartbeat")
class HeartbeatController {
@Get("/")
fun getHeartbeat(): HttpResponse<Unit> = HttpResponse.ok()
}
controller spec:
@MicronautTest
class HeartbeatControllerSpec {
@Inject
@field:Client("/")
lateinit var client: HttpClient
@Test
fun `Given the heartbeat endpoint, when it is called, then it should return Ok`() {
val rsp = client.toBlocking()
.exchange<Unit>("/api/heartbeat")
assertEquals(HttpStatus.OK, rsp.status)
}
}
The issue I'm having is the above test fails if there's no database configured because the application still tries to connect to a database as long as the datasources
config exists in the application.yml
.
I've tried @MicronautTest(startApplication = false)
but it doesn't make a difference.
For my 'unit tests', I solved this issue by not annotating the test with @MicronautTest
and initializing the service under test manually but in this case this is not possible because I'd like to call the controller with the HTTP client.
Is there a way to run application tests while at the same time not allowing the app to connect to a db?
In recent versions of Micronaut SQL (starting at 5.7.0) it is possible to disable the data sources via configuration. In Micronaut SQL 5.8.0 that behavior changed slightly from disabling all data sources at once, to disabling them independently.
The configuration syntax to do it is the following:
datasources.<datasource-name>.enabled: false
If you disable the data sources in your application-test.yml
they will be disabled for all tests that use @MicroanutTest
. For the tests that do need them, they can be enabled by setting the property back to true
with an annotation on the class, field or method.
For example, at the class level, it would look like this:
@MicronautTest
@Property(name = "datasources.<datasource-name>.enabled", value = "true")
class SomeTest { }