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 {

違反が何を言っているのかわかりません。これら 3 つの変数はどこで定義すればよいでしょうか。AnnouncerThread が違反に含まれていないのはなぜですか? 宣言を無駄に並べ替えようとしたのと同じ方法で宣言されています。

4

2 に答える 2

4

assertこれらの 3 つの最終変数を割り当てた直後に行っている呼び出しと関係があるようです。

PMD ドキュメント ( http://pmd.sourceforge.net/rules/controversial.html#DataflowAnomalyAnalysis ) は次のように述べています。

UR - 異常: 以前に定義されていなかった変数への参照があります

于 2009-07-19T20:26:54.160 に答える
0

それはかなり奇妙に見えます。興味深いことに、'new' を介して割り当てられたオブジェクトに対して定義された 3 つの変数すべてに対して発生し、その後 null かどうかをチェックします。「new」の結果は常に有効/nullではないことが期待されます-そうでない場合は、OutOfMemoryExceptionスローする必要があります。それが問題なのだろうか?

于 2009-07-19T20:21:11.003 に答える