Want "mockWebServer.dispatcher.clear()"
I have a JUnit file with several test functions that share a MockWebServer instance. The reason that they share it is that I need to declare it statically so that I can use Spring's @DynamicPropertySource to inject the MockWebServer's port number as Spring environment variable.
Anyway, Sometimes I enqueue a response and then test function A fails and does not take the response off the queue as expected. Then the next test function B is executed, I enqueue another response but the next call to the mock retrieves the first response in the queue - that was intended for the test function A.
What I propose is a mockWebServer.dispatcher.clear() method that empties the response queue. I could call this in a @BeforeEach annotated JUnit method.
Seems reasonable for QueueDispatcher but not Dispatcher.
In MockWebServer.enqueue(response: MockResponse) the "dispatcher" is cast to QueueDispatcher to calll its "enqueue()" method. I would propose the same for "clear()".
I also ran into this. Clearing the mock server response queue via a well-defined API would truly be a valuable feature enhancement for me.
To be clear on the status of this, enhancements for MockWebServer isn't a big focus for the OkHttp maintainers, but as this seems like a reasonable request, it's probably something that would be accepted given a nice simple clean PR. @lathspell Any interest in working on this?
see https://github.com/square/okhttp/pull/6736
Any news for this issue? A solution has been merged since July 2021, and yet it's still not part of any public release (as far as I can tell)
Released in 5 alphas.
Can someone paste the how to use solution in 5 alphas
Will this be in a non alpha release 4.11.0 is newer than your latest alpha but doesn't have this change ported to it.
I'm literally in this same predicament. I'm considering creating the mockwebserver with a static port and counting on that for my tests, but that seems error prone.
UPDATE: Luckily I'm starting a new project so I was able to switch to WireMock. It's fantastic for this and has a spring boot wrapper that sets property values at initialisation based on the server URL it creates at start-up.
@EnableWireMock({
// The line below configures an instance of the wiremock server, you can have multiple for difference external URLs,
// and assigns the server URL to a spring property named "external-service.base-url".
// The mock server also resets between tests instances so you don't need to manually clear it.
@ConfigureWireMock(name = "unique-server-name", property = "external-service.base-url"),
})
@SpringBootTest(classes = {
...
})
@EnableConfigurationProperties({
...
})
class MyServiceTest {
@InjectWireMock("unique-server-name")
WireMockServer wireMock;
....
Official Website: https://wiremock.org/ Spring boot library: https://github.com/maciejwalkowiak/wiremock-spring-boot