Skip to content

Instantly share code, notes, and snippets.

@arazabishov
Last active June 23, 2018 00:02
Show Gist options
  • Save arazabishov/f42d2dcf121564e9f5e4818f06cd881b to your computer and use it in GitHub Desktop.
Save arazabishov/f42d2dcf121564e9f5e4818f06cd881b to your computer and use it in GitHub Desktop.
A JUnit Rule for capturing screenshots using Spoon
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target(METHOD)
@Retention(RUNTIME)
public @interface CaptureScreenshots {
String before() default "";
String after() default "";
}
import android.app.Activity;
import android.support.test.rule.ActivityTestRule;
import android.text.TextUtils;
import com.squareup.spoon.Spoon;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class ScreenshotsRule<T extends Activity> extends ActivityTestRule<T> {
private Description description;
public ScreenshotsRule(Class<T> clazz) {
super(clazz);
}
@Override
public Statement apply(Statement base, Description description) {
this.description = description;
return super.apply(base, description);
}
@Override
public void finishActivity() {
if (getActivity() != null) {
beforeActivityFinished();
}
super.finishActivity();
}
public void screenshot(String tag) {
if (getActivity() == null) {
throw new IllegalStateException("Activity has not been started yet" +
" or has already been killed!");
}
Spoon.screenshot(getActivity(), tag, description.getClassName(),
description.getMethodName());
}
Override
protected void afterActivityLaunched() {
CaptureScreenshots captureScreenshots =
description.getAnnotation(CaptureScreenshots.class);
if (captureScreenshots != null) {
String tag = captureScreenshots.before();
if (TextUtils.isEmpty(tag)) {
tag = "before_" + description.getMethodName();
}
screenshot(tag);
}
}
protected void beforeActivityFinished() {
CaptureScreenshots captureScreenshots =
description.getAnnotation(CaptureScreenshots.class);
if (captureScreenshots != null) {
String tag = captureScreenshots.after();
if (TextUtils.isEmpty(tag)) {
tag = "after_" + description.getMethodName();
}
screenshot(tag);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment