I would like to unit test the behavior of my function which uses an asynchronous call to external API (using WebClient, but I doubt it is relevant). A simplified version of the flow of the function would be this
fun foo() {
if (conditionIsMet) {
thread(start = true) {
externalApi.post()
}
} else {
println("Hello World")
}
}
In my test file, I therefore have 2 tests, which test both if branches.
In the test where condition is met, I have mocked the external API call using MockWebServer, then use Awaitility to wait for the call to end
await().untilAsserted {
verify { externalApi.post() }
}
In the other test, I check that this call is not made :
verify (exactly = 0) { externalApi.post() }
When I run both tests separately, they both work without a hitch. The problems arise when I run them at the same time (I run all tests of the file, the same way that maven test
would do). Then, my second test fails, probably because it sees the call made in the other test.
I am not familiar with execution contexts in threads, so I have a shallow understanding of what is happening
What I have tried :
- Putting a lock on my test function, locking it on @BeforeEach and unlocking it on @AfterEach so that they would run sequentially
- replacing thread by coroutine in my code
- Naïvely put Thread.sleep() in my tests to force it to wait
None of this has worked, and I'm quite at a loss. Can anyone help ?