generated from micronaut-projects/micronaut-project-template
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add documentation for injecting an HttpClient
- Loading branch information
Showing
2 changed files
with
24 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters