开发者

Unit testing synchronization

Consider the following method:

/**
 * Set whether messages are printed to System.out.     * 
 * @param printOutput True to prin开发者_Python百科t, false for silent logging
 */
public void setPrintOutput(boolean printOutput) {
   // Synchronize to messages because this field is used when a message is received
   synchronized (messages) {
      this.printOutput = printOutput;
   }
}

This method is part of a set of several methods that involve messages, so I want to write a test that checks that this method is synchronized on messages. Does anyone know how I would do this?


I think this is beyond unit testing because the whole point of synchronization is to provide a certain type of connection between two distant pieces of code.

You can test the way it behaves with messages being null and not null, and that gives you full coverage. It won't say anything about whether your synchronization is semantically correct.


If you really want to unit test it then expose the message to the test code, get it's lock in one thread and check that you cannot aquire it from another thread (with timeout preventing deadlock). As @biziclop notices you should not test that. You can measure throughput, responsiveness but testing that some particular intrinsic lock is taken is too detailed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜