簡體   English   中英

如何對與Thread.interrupt一起使用的代碼進行可重復的單元測試?

[英]How to make repeatable unit tests of code that works with Thread.interrupt?

考慮一些代碼,例如,

 file = new RandomAccessFile(x, "r");
 file.getChannel().map(....)

並希望處理ClosedByInterruptException情況。 我對如何進行現實的,可重復的單元測試感到困惑。

為了進行測試,我需要以某種方式將該線程與其他線程進行同步,並使另一個線程在正確的時間調用Thread#interrupt。 但是,所有等待的原語都是可中斷的,並且可以清除中斷。

現在,我正在測試的代碼中有Thread.currentThread()。interrupt(根據單元測試的要求),但這與實際的異步中斷並不完全相同,不是嗎?

您對測試感興趣的是異常的處理,而不是創建異常的細節。 您可以將相關代碼移到另一個方法中,然后重寫該方法進行測試並引發相關異常。 這樣,您就可以測試結果,而不必擔心線程問題。

例如:

public class Foo {
    /**
     * default scope so it is visible to the test
     */
    void doMapping(RandomAccessFile raf) throws ClosedByInterruptException {
        file.getChannel().map(....);
    }

    public void processFile(File x) {
        RandomAccessFile raf = new RandomAccessFile(x, "r");
        doMapping(raf);
    }
...
}

public class FooTest {
    @Test
    void testProcessFile() {     
        Foo foo = new Foo() {
            @Override
            void doMapping(RandomAccessFile raf) throws ClosedByInterruptException {
                throw new ClosedByInterruptException(...);
            }
        };

        ...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM