micronaut-projects / micronaut-core

Micronaut Application Framework
http://micronaut.io
Apache License 2.0
6k stars 1.04k forks source link

Injected HttpClient fails in test if rebuildContext is set to true (with reproducer) #5453

Open oscarfh opened 3 years ago

oscarfh commented 3 years ago

I faced this issue during development and I was able to extract to a reproducer that can be seen here: https://github.com/oscarfh/micronaut-test-error

Simply check it our and execute the DemoTest test. There you will see two identical tests, if executed together, the first passes, the second always fails. If executed separately, both pass.

There is no much magic there, injecting an httpclient and calling the controller that exist in the application. The issue seems to be the rebuildContext flag that is set on line 25. (Remove that and you will get green tests).

This feel related to this issue I once found (and was fixed): https://github.com/micronaut-projects/micronaut-core/issues/2138

graemerocher commented 3 years ago

I don't believe there is much we can do about this rebuildContext is incompatible with @TestInstance(TestInstance.Lifecycle.PER_CLASS) as you have on your test since it prevents re-injecting all dependencies for each test

oscarfh commented 3 years ago

@graemerocher The problem persists even after removing @TestInstance(TestInstance.Lifecycle.PER_CLASS).

nayavu commented 3 years ago

I've got the same issue.

As an ugly workaround, I do the following:

@MicronautTest(rebuildContext = true)
class Test {
    @field:Inject
    lateinit var embeddedServer: EmbeddedServer

    @field:Inject
    @field:Client("/")
    lateinit var client: RxHttpClient

    @BeforeEach
    fun initialise() {
        if (firstRun) {
            firstRun = false
        } else {
            embeddedServer.refresh()
        }
    }

   // tests 

    companion object {
        @JvmStatic
        var firstRun: Boolean = true
    }
}