单元测试同步

发布于 2024-10-17 13:12:24 字数 438 浏览 2 评论 0原文

考虑以下方法:

/**
 * 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暖阳 2024-10-24 13:12:24

我认为这超出了单元测试的范围,因为同步的全部目的是在两个遥远的代码片段之间提供某种类型的连接。

您可以在 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.

余厌 2024-10-24 13:12:24

如果您确实想对其进行单元测试,则将消息公开给测试代码,将其锁定在一个线程中,并检查是否无法从另一个线程获取它(超时可以防止死锁)。正如 @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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文