Skip to content

Instantly share code, notes, and snippets.

@ankushg
Created April 6, 2018 23:26
Show Gist options
  • Save ankushg/72b7f8ed88d64bf16c079314f5cd29b2 to your computer and use it in GitHub Desktop.
Save ankushg/72b7f8ed88d64bf16c079314f5cd29b2 to your computer and use it in GitHub Desktop.
ShadowResourcesCompat
import com.ankushg.example.BuildConfig
import com.ankushg.example.shadows.ShadowResourcesCompat
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(
constants = BuildConfig::class,
packageName = "com.ankushg.example",
sdk = intArrayOf(21),
shadows = arrayOf(
ShadowResourcesCompat::class
)
)
abstract class BaseRobolectricTest {
// common code here
}
package com.ankushg.example.shadows;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.FontRes;
import android.support.annotation.NonNull;
import android.support.v4.content.res.ResourcesCompat;
import java.util.HashMap;
import java.util.Map;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
/**
* Mocks out ResourcesCompat so getFont won't actually attempt to look up the FontRes as a real
* resource, because of issues with Robolectric.
* <p>
* See: https://github.com/robolectric/robolectric/issues/3590
*/
@Implements(ResourcesCompat.class) public class ShadowResourcesCompat {
private static Map<Integer, Typeface> FONT_MAP = new HashMap<>();
@Implementation
public static Typeface getFont(@NonNull Context context, @FontRes int id) {
return FONT_MAP.computeIfAbsent(id, ShadowResourcesCompat::buildTypeface);
}
private static Typeface buildTypeface(@FontRes int id) {
return Typeface.DEFAULT;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment