1

我有以下 JUnit 测试:

@Test
public void testRunLocalhost() throws IOException, InterruptedException {
    // Start an AnnouncerThread
    final AnnouncerThread announcer = new AnnouncerThread();
    announcer.start();

    // Create the socket and listen on the right port.
    final DatagramSocket socket = new DatagramSocket();
    assert(socket != null);

    // Create a packet to send.
    final DatagramPacket packet = new DatagramPacket(new byte[0], 0, InetAddress.getByName(AnnouncerThread.GROUP), AnnouncerThread.PORT);
    assert(packet != null);

    // Send the packet.
    socket.send(packet);

    // Listen for the IP from the server.
    final DatagramPacket receivedPacket = new DatagramPacket(new byte[256], 256);
    socket.setSoTimeout(2000); // Only wait 2 seconds.
    socket.receive(receivedPacket);
    socket.close();

    // Get localhost's address.
    final InetAddress localhost = InetAddress.getLocalHost();
    assert(localhost != null);

    // Compare the receive IP to the localhost IP.
    final String receivedIP = new String(receivedPacket.getData());
    if (!receivedIP.startsWith(localhost.getHostAddress())) {
        fail("Received IP: '" + receivedIP + "' not the same as localhost: '" + localhost.getHostAddress() + "'");
    }

    announcer.shutdown();
    announcer.join();
}

并且 PMD 给出了以下违规行为:

Found 'UR'-anomaly for variable 'socket' (lines '36'-'36').
Found 'UR'-anomaly for variable 'localhost' (lines '36'-'36').
Found 'UR'-anomaly for variable 'packet' (lines '36'-'36').

我文件中的第 36 行是定义方法的行:

public void testRunLocalhost() throws IOException, InterruptedException {

我不明白这些违规行为在说什么。我应该在哪里定义这三个变量?为什么 AnnouncerThread 不在违规中?它的声明方式与我尝试重新排序声明无济于事的方式相同。

4

2 回答 2

4

它似乎与assert您在分配这三个最终变量后立即进行的调用有关。

PMD 文档(http://pmd.sourceforge.net/rules/controversial.html#DataflowAnomalyAnalysis)说:

UR - 异常:存在对之前未定义的变量的引用

于 2009-07-19T20:26:54.160 回答
0

这看起来相当奇怪。有趣的是,它发生在为通过“new”分配的对象定义的所有三个变量上,然后您检查它们是否为空。我希望“新”的结果始终有效/不为空 - 否则OutOfMemoryException应该抛出一个。是这个问题吗,我想知道吗?

于 2009-07-19T20:21:11.003 回答