Last active
November 22, 2019 12:50
-
-
Save pedrovgs/c6072236f45c68926d70423b2f3e3e38 to your computer and use it in GitHub Desktop.
Interface you can import from your tests to be able to use screenshot testing for Android with different resolutions easily
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity | |
import android.app.Dialog | |
import android.content.Context | |
import android.view.View | |
import androidx.fragment.app.Fragment | |
import androidx.test.platform.app.InstrumentationRegistry | |
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation | |
import com.facebook.testing.screenshot.Screenshot | |
import com.facebook.testing.screenshot.ViewHelpers | |
import com.facebook.testing.screenshot.internal.TestNameDetector | |
interface ScreenshotTest { | |
val context: Context get() = InstrumentationRegistry.getInstrumentation().targetContext | |
fun compareScreenshot( | |
activity: Activity, | |
heightInPx: Int? = null, | |
backgroundColor: Int = R.color.white | |
) { | |
waitForAnimationsToFinish() | |
val view = activity.findViewById<View>(android.R.id.content) | |
runOnUi { | |
view.setBackgroundResource(backgroundColor) | |
} | |
compareScreenshot(view = view!!, heightInPx = heightInPx) | |
} | |
fun compareScreenshot(dialog: Dialog) { | |
val window = dialog.window | |
if (window != null) { | |
waitForAnimationsToFinish() | |
compareScreenshot(window.decorView) | |
} | |
} | |
fun compareScreenshot(view: View, heightInPx: Int? = null, name: String? = null) { | |
waitForAnimationsToFinish() | |
Device.values().forEach { | |
val heightInDp = heightInPx ?: it.height | |
runOnUi { | |
ViewHelpers.setupView(view) | |
.setExactHeightPx(heightInDp) | |
.setExactWidthPx(it.width) | |
.layout() | |
} | |
val testName = name ?: TestNameDetector.getTestName() | |
Screenshot | |
.snap(view) | |
.setName("${TestNameDetector.getTestClass()}_${testName}_${it.name}") | |
.setDescription("${it.name}-${it.width}x${it.height}") | |
.record() | |
} | |
} | |
fun compareScreenshot(fragment: Fragment, heightInPx: Int) = | |
compareScreenshot(fragment.view!!, heightInPx) | |
fun waitForAnimationsToFinish() { | |
getInstrumentation().waitForIdleSync() | |
} | |
fun runOnUi(block: () -> Unit) { | |
getInstrumentation().runOnMainSync { block() } | |
} | |
} | |
@Suppress("unused") | |
enum class Device(val width: Int, val height: Int) { | |
SMALLEST(640, 1136), | |
HUAWEI_P8_LITE(720, 1280), | |
PIXEL4_XL((1440 / 1.82).toInt(), (3040 / 1.82).toInt()), | |
SAMSUNG_GALAXY_S7_EDGE((1440 / 1.81).toInt(), (2560 / 1.81).toInt()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment