Skip to content

Commit

Permalink
Add documentation for injecting an HttpClient
Browse files Browse the repository at this point in the history
  • Loading branch information
timyates committed Feb 14, 2023
1 parent 1ae8b9e commit 82271bc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/main/docs/guide/testing.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
When you create a Micronaut Framework application (either via https://launch.micronaut.io or the command line application), it creates a https://docs.micronaut.io/latest/api/io/micronaut/context/annotation/ContextConfigurer.html[ContextConfigurer] with enables https://docs.micronaut.io/latest/guide/index.html#eagerInit[eager singleton initialization].

As tests annotated with `@MicronautTest` are implicitly in the `Singleton` scope, this can cause problems injecting some beans (for example an `HttpClient`) into your test class.

To avoid this, you can either disable eager singleton initialization for your tests, or you will need to manually get an instance of the bean you would normally inject. As an example, to get an `HttpClient` you could do:

[source,java]
----
@Inject
EmbeddedServer server; // <1>
Supplier<HttpClient> client = SupplierUtil.memoizedNonEmpty(() ->
server.getApplicationContext().createBean(HttpClient.class, server.getURL())); // <2>
@Test
void testEagerSingleton() {
Assertions.assertEquals("eager", client.get().toBlocking().retrieve("/eager")); // <3>
}
----

<1> Inject the `EmbeddedServer` as normal
<2> Create a `Supplier` that will create the `HttpClient` when it is first called
<3> Use the `Supplier` to get the `HttpClient` and make the request
1 change: 1 addition & 0 deletions src/main/docs/guide/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ refresh: Refresh scope
events: Events
context: Context Provider
docker: Docker Support
testing: Testing
repository: Repository

0 comments on commit 82271bc

Please sign in to comment.