Testing with Thread.sleep

后端 未结 6 1789
囚心锁ツ
囚心锁ツ 2021-01-11 16:28

What are the recommended approaches to using Thread.sleep() to speed up tests.

I am testing a network library with a retry functionality when connection

6条回答
  •  被撕碎了的回忆
    2021-01-11 16:38

    I would argue why are you trying to test Thread.sleep. It seems to be me you're trying to test the behaviour as a consequence of some event.

    i.e. what happens if:

    • connection timeout
    • connection dropped

    If you model code based on events then you can test what should happen should a particular event occurred rather than having to come up with a construct that masks the concurrent API calls. Else what are you really testing? Are you testing how your application reacts to different stimuli or simply testing the JVM is working correctly?

    I agree with the other readers that sometimes it's useful to put an abstraction around any code time or thread related i.e. Virtual clock http://c2.com/cgi/wiki?VirtualClock so you can mock out any timing/concurrent behaviour and concentrate on the behaviour of the unit itself.

    It also sounds like you should adopt a state pattern so you object has specific behaviour depending on what state it's in. i.e AwaitingConnectionState, ConnectionDroppedState. Transition to different states would be via the different events i.e. timeout, dropped connection etc. Not sure if this overkill for your needs but it certainly removes a lot of conditional logic which can make the code more complicated and unclear.

    If you approach this way, then you can still test behaviour at the unit level whilst still testing in situ with an integration test or acceptance test later.

提交回复
热议问题