2014-01-24 51 views
1

我正在使用JUnit v4作爲測試框架。我想知道如何在測試用例的運行時設置超時?如何在運行時在JUnit測試用例中設置超時

我正在使用Parameterized測試。其中我有一個列表Scenario,其中包含超時值和其他文件。這些Scenario中的每一個都可能具有不同的-2超時。

timeout參數不幫我實現這一點。

@Test(timeout = getTimeOut()) 
public void secureLoginWithLongUsername() { 
    // Test case goes here 

} 

private final long getTimeOut() { 
    // I am doing some processing here to calculate timeOut dynamically 
    long timeOut = scenario.getTimeOut(); 
    return timeOut; 
} 

@Parameters 
public static Collection<Scenario[]> getParameters() { 

    List<Scenario[]> scenarioList = new ArrayList<Scenario[]>(); 
    Configuration config = new Configuration(); 
    List<Scenario> scenarios = config.getScenarios(); 
    for (Scenario scenario : scenarios) { 
     scenarioList.add(new Scenario[] { scenario }); 
    } 

    return scenarioList; 
} 

public class Configuration { 
    private List<Scenario> scenarios; 
    //Some processing here 
    public List<Scenario> getScenarios() { 
     return scenarios; 
    } 
} 

public class Scenario { 
    private long timeOut; 
    private String name; 
    //Some more fields here 
} 

請幫助我確定任何替代方法來動態設置超時。

+0

請問[超時規則(https://github.com/junit-team/junit/wiki/Timeout-for-tests #超時規則 - 適用於整個測試類)的幫助? –

+0

讓我重新定義我的問題。抱歉給你帶來不便。 –

+0

@MoritzPetersen:請看看我更新的問題。 –

回答

1

我想,你需要建立它自己,如:

private Timer timer; 

@After 
public void terminateTimeout() { 
    if (timer != null) { 
     timer.cancel(); 
     timer = null; 
    } 
} 

@Test 
public void testTimeout() throws Exception { 
    setTimeout(1000); 
    // run test... 
} 

private void setTimeout(int duration) { 
    final Thread currentThread = Thread.currentThread(); 
    timer = new Timer(); 
    timer.schedule(new TimerTask() { 
     @Override 
     public void run() { 
      currentThread.interrupt(); 
     } 
    }, duration); 
} 
+2

只想問你幾個問題。 (1)用當前線程玩是無害的嗎?我希望線程管理必須由JUnit在內部處理。它有任何副作用嗎? (2)在指定的超時後,如何將測試用例標記爲失敗?不知何故,我需要調用'org.junit.Assert.fail()'方法。 –

相關問題