单元测试同步
考虑以下方法:
/**
* Set whether messages are printed to System.out. *
* @param printOutput True to print, 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;
}
}
此方法是涉及消息的一组方法的一部分,因此我想编写一个测试来检查此方法是否在消息上同步。有谁知道我会怎么做?
Consider the following method:
/**
* Set whether messages are printed to System.out. *
* @param printOutput True to print, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这超出了单元测试的范围,因为同步的全部目的是在两个遥远的代码片段之间提供某种类型的连接。
您可以在
messages
为 null 和非 null 的情况下测试它的行为方式,这样您就可以完全覆盖。它不会说明您的同步在语义上是否正确。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.如果您确实想对其进行单元测试,则将
消息
公开给测试代码,将其锁定在一个线程中,并检查是否无法从另一个线程获取它(超时可以防止死锁)。正如 @biziclop 注意到的那样,您不应该测试它。您可以测量吞吐量、响应能力,但测试是否采用某些特定的内在锁过于详细。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.