Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught Exception Handler - UiAutomator

I would like to have UiAutomator take a screenshot when a test fails. The way I currently have this set up is like so:

    @Override
protected void setUp() throws Exception {
    System.out.println("Beginning setup...");
    testFailed = true;
}

@Override
protected void tearDown() throws Exception {
    if(testFailed)
        getUiDevice().takeScreenshot("/sdcard/Pictures/Screenshots/failure.jpg");
}

then the individual test works like this

public void testExample(){
  /* do stuff */
  testFailed = false;
}

the idea is that if an exception is thrown, testFailed is never set to false, and tearDown take a screenshot when it is called after the test.

I was really hoping to be able to add a testListener, or uncaught exception handler into my code for a more elegant solution to this problem. However, UiAutomator has its own uncaught exception handler that overrides the one I tried to implement. I can add my uncaught exception handler but it's just ignored.

Is there any way that I can add an uncaught exception handler, that will intercept exceptions between where they are thrown and UiAutomator's uncaught exception handler, then pass them along (to UiAutomator)?

Is there another way I can listen for a test failing / an exception being thrown without specifically adding that Boolean into the end of every test?

like image 733
user3829753 Avatar asked Sep 24 '26 19:09

user3829753


1 Answers

Instead of calling getUiDevice().takeScreenshot() in teardown put this inside a function - say foo() and call it when exception happens.

now put the code you want to test in a try catch block and in catch call foo(). somewhat like this -

try{
//add your test code here
}
catch(Exception e){
foo();
//and if you want to throw exception again so your current test flow is not disturbed then add
throw e;
}
like image 145
JohnSmith Avatar answered Sep 27 '26 09:09

JohnSmith