Skip to content

Instantly share code, notes, and snippets.

@veena14cs
Last active October 29, 2019 15:51
Show Gist options
  • Save veena14cs/c772d1a111226bcaa91d7f98cef44e4b to your computer and use it in GitHub Desktop.
Save veena14cs/c772d1a111226bcaa91d7f98cef44e4b to your computer and use it in GitHub Desktop.
@RunWith(AndroidJUnit4::class)
class UrlImageParserTest {
@Inject
lateinit var mockImageLoader: ImageLoader // Inject the mock ImageLoader provided below.
private lateinit var launchedActivity: Activity
@get:Rule
var activityTestRule: ActivityTestRule<UrlImageParserTestActivity> = ActivityTestRule(
UrlImageParserTestActivity::class.java, /* initialTouchMode= */ true, /* launchActivity= */ false
)
@Before
fun setUp() {
mockImageLoader = Mockito.mock(ImageLoader::class.java)
Intents.init()
val intent = Intent(Intent.ACTION_PICK)
launchedActivity = activityTestRule.launchActivity(intent)
}
// Prepares the ImageLoader for receiving the specified bitmap for the given URL.
private fun prepareImageLoaderForResponse(expectedUrl: String, bitmap: Bitmap) {
val imageView = activityTestRule.activity.findViewById(R.id.test_url_parser_image_view) as ImageView
doAnswer { invocation ->
val customTarget: CustomTarget<Bitmap> = invocation.getArgument(1)
customTarget.onResourceReady(bitmap, /* transition= */ null)
imageView.setImageBitmap(bitmap)
}.`when`(mockImageLoader).load(expectedUrl, any())
}
@Test
fun testImageLoader_returnSuccess() {
var bitmap: Bitmap? = null
var drawable: Drawable? = null
val target = object : CustomTarget<Bitmap>() {
override fun onLoadCleared(placeholder: Drawable?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
drawable = BitmapDrawable(activityTestRule.activity.getResources(), resource);
bitmap = resource
}
}
mockImageLoader.load(OK_IMAGE_URL,target)
prepareImageLoaderForResponse(OK_IMAGE_URL, bitmap!!)
}
@After
fun tearDown() {
Intents.release()
}
@Module
class TestModule {
@Provides
fun provideImageLoader(): ImageLoader {
return mock(ImageLoader::class.java) // return a Mockito mock of ImageLoader
}
}
companion object {
const val FAKE_IMAGE_URL = ""
const val OK_IMAGE_URL = "https://teorico.net/images/test-dgt-1.png"
}
}
@veena14cs
Copy link
Author

Screenshot 2019-10-29 at 6 47 59 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment