2017-09-05 26 views
1

迄今爲止我發現了2種設置JUnit測試超時的方法。或者使用:使用反射設置JUnit測試超時

@Test(timeout=XXX) 

或者使用類似:

@ClassRule 
public static Timeout timeoutRule = new Timeout(XXX, TimeUnit.MILLISECONDS); 

就我而言,我有一個測試運行的主類來運行我所有的測試套件,這樣我就可以執行測試作爲可執行的jar。 我希望這個跑步者使用反射來設置超時的超時時間。

可以嗎?

回答

0

您可以將超時功能添加到自定義測試運行,像這樣:

public class TimeoutTestRunner extends BlockJUnit4ClassRunner { 

    public TimeoutTestRunner(Class<?> clazz) throws InitializationError { 
     super(clazz); 
    } 

    @Override 
    protected Statement withPotentialTimeout(FrameworkMethod method, Object test, Statement next) { 
     return FailOnTimeout.builder() 
       // you'll probably want to configure/inject this value rather than hardcode it ... 
       .withTimeout(1, TimeUnit.MILLISECONDS) 
       .build(next); 
    } 
} 

使用該測試運行在下面的測試案例的測試...

@RunWith(TimeoutTestRunner.class) 
public class YourTest { 

    @Test 
    public void willTimeout() throws InterruptedException { 
     Thread.sleep(50); 
     assertTrue(true); 
    } 

    @Test 
    public void willNotTimeout() throws InterruptedException { 
     assertTrue(true); 
    } 
} 

...會表現如下:

  • willTimeout:將失敗,TestTimedOutException
  • willNotTimeout:將通過

雖然你將需要你的測試通過這個亞軍運行,你將能夠控制自己的超時從一個地方設置和提供定製超時推導策略,如if test name matches <some regex> then timeout is x else ...

+0

無法擴展BlockJUnit4ClassRunner,因爲我的跑步者已經在擴展另一個類。 有沒有其他辦法可以做到這一點,而不必延長這一點? 可能會在類中插入一個新的超時字段,或者在運行時將測試註釋的超時值插入... –

+0

@AlexanderRumanovsk:我真的不認爲您可以隨時更改測試類。我認爲一個定製的跑步者適合你的用例。你寫道:「我的跑步者已經在擴展另一個類」,所以它必須(在層次結構的某個地方)擴展'org.junit.runner.Runner',所以如果一切都失敗了(例如,如果你使用的跑步者沒有一個簡單的你可以總是覆蓋'run()'方法,並且在超時塊中將調用包裝爲'super.run()',它有一個'run()'方法。 – glytching