2009-07-19 172 views
0

我有以下的JUnit测试:PMD规则DataflowAnomalyAnalysis奇怪

@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在违规行为?它的声明与我尝试重新排列声明无效的方式相同。

回答

3

它似乎与分配这三个最终变量后正确调用的assert调用有关。

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

UR - 异常:有一个变量的引用之前

+0

卸下断言摆脱了侵犯,这不是定义。 – 2009-07-19 20:33:17

+0

是PMD上的一个错误吗? – 2013-10-08 16:26:04

+0

是的,'DataflowAnomalyAnalysis'已经过时了。断言的这个特定问题是[最近修复并将成为PMD 6.0.0的一部分](https://github.com/pmd/pmd/pull/420),但仍然存在[一系列悬而未决的问题](https ://github.com/pmd/pmd/labels/in%3Adata-flow) – Johnco 2017-07-11 23:27:34

0

这看起来很奇怪。有趣的是,对于通过'new'分配的对象定义的所有三个变量都会发生,然后您检查是否为空。我希望'new'的结果始终为有效/非空 - 否则应该抛出OutOfMemoryException。这个问题,我想知道吗?