我有几个课程可以测试我的应用程序。如果它持续超过4秒,我想测试失败。我的代码破坏了测试,但在某些情况下它不会执行下一个测试类。
当我写(它与超时无关,只是失败()的一个例子)时:
public void testSmth() {
fail("msg");
}
故障跟踪为空,它会中断测试并启动另一个测试。但是当我想让它像超时一样时:
public void testSmth() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
fail("msg");
}
}, 4000);
// some tests (that even lasts more than 4 secons) like clickOnImage() etc.
}
它打破了测试,但它没有执行下一个测试,而在故障跟踪中则有:
测试未能完成。原因:'由于''junit.framework.AssertionFailedError''导致仪表运行失败。检查设备logcat以获取详细信息
在LogCat中我得到了:
07-26 11:46:07.428:E / AndroidRuntime(6195):致命异常:Timer-1
07-26 11:46:07.428:E / AndroidRuntime(6195):junit.framework.AssertionFailedError:msg
07-26 11:46:07.428:E / AndroidRuntime(6195):在junit.framework.Assert.fail(Assert.java:47)
07-26 11:46:07.428:E / AndroidRuntime(6195):at java.util.Timer $ TimerImpl.run(Timer.java:284)
或者还有其他方法可以做我想要的事情?
感谢。
答案 0 :(得分:1)
您必须使用以下内容覆盖runTest()方法:
[编辑] 此代码创建一个新线程并在其上运行实际测试。 Future类允许我们对该线程的执行施加超时,并且当达到超时时,它将被停止。它还负责捕获异常。 (我是否提到其余的测试仍将继续运行?)
如果您想使用此超时来确保测试不会在测试代码中的任何地方保持“挂起”,这将非常有用。
public class MyTestClass extends
ActivityInstrumentationTestCase2<EditorActivity> {
@Override
public void runTest() throws Throwable {
final Throwable[] exceptions = new Throwable[1];
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() throws Exception {
try {
doRunTest();
}
catch (Throwable t) {
exceptions[0] = t;
}
return Boolean.TRUE;
}
};
int timeOutMinutes = 10;
String testCaseName = String.format("%s.%s", getClass().getName(), getName());
Future<Object> future = executor.submit(task);
try {
future.get(timeOutMinutes, TimeUnit.MINUTES);
} catch (TimeoutException ex) {
Assertions.fail("[Test method timed out after " + timeOutMinutes + " minutes.]\n" + testCaseName);
} catch (Throwable e) {
throw e;
} finally {
future.cancel(true); // may or may not desire this
}
if (exceptions[0] != null) {
throw exceptions[0];
}
}
private void doRunTest() throws Throwable {
super.runTest();
}
}
答案 1 :(得分:1)
如果您只是想在达到超时的情况下进行测试失败,那就足够了:
public void test1() throws Exception {
long start = System.currentTimeMillis();
solo.sleep(5000);
if (System.currentTimeMillis() - start > 4000) {
fail("msg");
}
}
public void test2() throws Exception {
long start = System.currentTimeMillis();
solo.sleep(3000);
if (System.currentTimeMillis() - start > 4000) {
fail("msg");
}
}
在执行过程中很难打破测试,你也可以在每个命令后检查超时,但检查它需要时间,你的测试方法会持续更长时间。