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