Agenda
of this blog: To
discuss about how to re-run your failed automation scripts without any manual
interference using JUnit- Unit test framework.
What
is the need: When you
write your automation script it might happen that some of your test script may
get failed due any reason, it might be due to some internet issues, or UI
issues or locator changes or might be some issue with the coding itself or some
sporadic issues. So in that case we may need to re-run the failed test case
without triggering those again manually. This feature is supported by your Unit
test framework TestNg/JUnit, here we will be discussing considering the JUnit
as the Unit test Framework.
Approach we will follow is:
1. Write
a class which will be having the implementation of the retry functionalities by
using a listener for JUnit i.e TestRule .A
TestRule is an alteration of how a test method, or set of test methods, is run
and reported.
2. Then
use the implemented feature in your tests by using @Rule which is part of JUnit: Basically Rules allow very flexible addition or redefinition of the behavior of each test method in a test
class. Testers can reuse or extend Rules, or can write their own.
Now let us have
a look at the code snippet:
package com.junitRetry;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class RetryAnalyzer {
public class Retry implements TestRule {
private int retryCount;
public Retry(int retryCount) {
this.retryCount = retryCount;
}
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;
//Retry logic goes here
for (int i = 0; i < retryCount; i++) {
try {
base.evaluate();
return;
} catch (Throwable ex) {
caughtThrowable = ex;
System.err.println(description.getDisplayName() + ": run iteration
number " + (i+1) + " failed");
}
}
System.err.println(description.getDisplayName() + ": Quiting after
" + retryCount + " failures");
throw caughtThrowable;
}
};
}
}
@Rule
public Retry retry = new Retry(4);
@Test
public void test1() {
System.out.println("Test Passed");
}
@Test
public void test2() {
System.out.println("FAILED test");
Assert.fail();
}
}
Visit for More Automation Related Discussion:
https://www.youtube.com/channel/UCKSk4gkmO3LXcW17hFUkmcQ/videos
Visit for More Automation Related Discussion:
https://www.youtube.com/channel/UCKSk4gkmO3LXcW17hFUkmcQ/videos
No comments:
Post a Comment