I'm writing a test for my server with Mockito. In my test, instead of a real Messenger (which would try to send actual HTTP messages to a client), it uses a mock Messenger. The problem I'm facing is, one of the server methods basically does this (in a thread created by the server, not the test thread):
void serverMethod() {
MyObject object;
object.setProperty(1);
messenger.send(object);
object.setProperty(2);
}
And in my test, I'm trying to verify that object.getProperty()
would return 1 at the time it's passed to messenger.send()
, not 2. I've tried both custom argument matchers and argument captors, and both actually pass some of the time, but they don't pass reliably because the test thread is racing against the server thread which is about to modify "object" so that object.getProperty()
returns 2.
I've already verified that the app code doesn't have an actual bug, because the real Messenger immediately serializes "object" to send to the client, effectively copying the value of "property" so any later modifications don't matter.
I'm well aware that this may be one of those instances when, although the app code is working fine, it has poor testability, so the only way to write a good deterministic test for this (without changing the whole testing infrastructure) is to modify the app code to improve testability (in this case, passing an immutable object instead of this mutable one that's about to be modified and reused).
My question is, is there any clever way to properly test this without touching the app code?