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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With