문제
나의 능력을 테스트하는 수업이 거의 없습니다. 4 초 이상 지속되면 테스트를 실패하고 싶습니다. 내 코드는 테스트를 해제하지만 몇 가지 경우 다음 테스트 클래스를 실행하지 않습니다.
내가 쓸 때 (시간 초과에 아무런 관련이 없지만, FAIL ()의 예) :
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 / AndroAdRuntime (6195) : 치명적인 예외 : 타이머 -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) : java.util.timer $ timerimpl.run (Timer.java:284)
또는 어쩌면 내가 원하는 것을 할 수있는 또 다른 방법이 있습니까?
감사합니다.
해결책
시간 초과에 도달 할 때 테스트를 실패하고 싶다면 다음이 있어야합니다.
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");
}
}
.
실행 중에 테스트를 해제하기가 어렵습니다. 모든 명령 후에 시간 초과를 확인할 수도 있지만 시간이 걸리고 테스트 방법이 더 오래 지속됩니다.
다른 팁
이와 같이 runtest () 메소드를 무시해야합니다.
[편집] 이 코드는 새 스레드를 만들고 실제 테스트를 실행합니다.미래의 클래스를 사용하면이 스레드의 실행에 시간 초과를 넣을 수 있으며 시간 초과에 도달하면 중지됩니다.그것은 또한 예외를 잡는 것을 돌보아줍니다.(나머지 테스트가 계속 실행될 것임을 언급 했습니까?)
이 시간 초과를 사용하여 테스트가 테스트 된 코드의 어딘가에 '교수형'되지 않았는지 확인하려는 경우 매우 유용합니다.
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();
}
}
.