下面列出了怎么用android.support.test.InstrumentationRegistry的API类实例代码及写法,或者点击链接到github查看源代码。
@Before
public void setUp() throws Exception {
((TestComponent) SensorbergTestApplication.getComponent()).inject(this);
tested = spy(new SensorbergService());
tested.onCreate();
tested.bluetoothPlatform = new TestBluetoothPlatform();
fileManager = spy(fileManager);
tested.fileManager = fileManager;
tested.transport = Mockito.mock(Transport.class);
Intent startIntent = SensorbergServiceIntents.getStartServiceIntent(InstrumentationRegistry.getContext(), TestConstants.API_TOKEN_DEFAULT);
tested.onStartCommand(startIntent, -1, -1);
TestGenericBroadcastReceiver.reset();
TestGenericBroadcastReceiver2.reset();
}
@Test
public void escapeSpecialCharsTest() throws Exception {
Context context = InstrumentationRegistry.getTargetContext();
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open("escape_chars.xml");
XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null).build();
inputStream.close();
try {
String formatted = xmlToJson.toFormattedString();
new JSONObject(formatted);
} catch (JSONException exception) {
exception.printStackTrace();
assertTrue("invalid JSON", false);
}
}
@Test
public void fullscreen_disabledOnPortrait() throws Throwable {
rule.runOnUiThread(new Runnable() {
@Override
public void run() {
rule.getActivity()
.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
});
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
rule.runOnUiThread(new Runnable() {
@Override
public void run() {
final View decorView = rule.getActivity().getWindow().getDecorView();
assertThat(decorView.getSystemUiVisibility(),
not(hasFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)));
}
});
}
@Test
public void test_enter_exit_action() throws Exception {
ResolveResponse resolveResponse = gson
.fromJson(Utils.getRawResourceAsString(com.sensorberg.sdk.test.R.raw.resolve_response_enter_exit_action, InstrumentationRegistry
.getContext()), ResolveResponse.class);
Mockito.when(mockRetrofitApiService.getBeacon(Mockito.anyString(), Mockito.anyString(), Matchers.<TreeMap<String, String>>any()))
.thenReturn(Calls.response(resolveResponse));
ResolverListener testListener = new ResolverListener() {
@Override
public void onResolutionFailed(Throwable cause, ScanEvent scanEvent) {
Assert.fail(cause.getMessage());
}
@Override
public void onResolutionsFinished(List<BeaconEvent> events) {
Assertions.assertThat(events).hasSize(1);
}
};
tested.setListener(testListener);
tested.resolve(TestConstants.RESOLVABLE_ENTRY_EVENT_WITH_ID_3);
}
@Test
public void testCameraStubMultipleTimes() throws IOException {
targetFile = new File(activity.getExternalCacheDir(), RESULT_JPG);
assertFalse(targetFile.exists());
Uri pictureUri = EspFilesTool.copyFileFromAssetsToExternalCacheDir(SAMPLE_JPG, RESULT_JPG);
espCameraStub.register(pictureUri);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
activity.startForResult(intent, REQUEST_CODE);
requestCodeTextView.assertTextIs(String.valueOf(REQUEST_CODE));
InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
((TextView) getActivity().findViewById(OnActivityResultActivity.requestCodeResource)).setText("");
}
});
requestCodeTextView.assertTextIs("");
activity.startForResult(intent, REQUEST_CODE);
requestCodeTextView.assertTextIs(String.valueOf(REQUEST_CODE));
}
@Override
protected void beforeActivityLaunched() {
super.beforeActivityLaunched();
App.BaseApplicationComponent component = DaggerMockApplicationComponent.builder()
.mockApplicationModule(new MockApplicationModule((App) InstrumentationRegistry.getTargetContext().getApplicationContext()))
.build();
App.overrideComponent(component);
User bobUser = new User("Bob", "bob", "http://assets.rollingstone.com/assets/images/list_item/bob-marley-20110420/square.jpg");
when(component.twitterService().getMyDetails()).thenReturn(Observable.just(bobUser));
timelineItems = new ArrayList<>();
timelineItems.add(new TimelineItem("10m", "hello", bobUser));
when(component.twitterService().getTimelineItems()).thenReturn(Observable.just(timelineItems));
when(component.twitterService().getCurrentUser()).thenReturn(bobUser);
when(component.twitterService().sendTweet(anyString())).thenReturn(Observable.just(true));
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.packt.madev", appContext.getPackageName());
}
@Test
public void testSendEventShouldFail () throws Exception {
WebViewApp.setCurrentApp(null);
final ConditionVariable cv = new ConditionVariable();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
WebViewApp.setCurrentApp(new WebViewApp());
WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
WebViewApp.getCurrentApp().setWebAppInitialized(true);
cv.open();
}
});
boolean cvsuccess = cv.block(10000);
assertTrue("ConditionVariable was not opened successfully", cvsuccess);
boolean success = WebViewApp.getCurrentApp().sendEvent(MockEventCategory.TEST_CATEGORY_1, MockEvent.TEST_EVENT_1);
assertFalse("sendEvent -method should've returned false", success);
assertFalse("WebView invokeJavascript should've not been invoked but was (webviewapp is not loaded so no call should have occured)", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
assertNull("The invoked JavaScript string should be null (webviewapp is not loaded so no call should have occured)", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
@Before
public void initFixture() {
final byte[] SALT = new byte[] {
104, -12, 112, 82, -85, -10, -11, 61, 15, 54, 44, -66, -117, -89, -64, 110, -53, 123, 33
};
// Prepare PreferenceObfuscator instance
Context ctx = InstrumentationRegistry.getTargetContext();
sp = ctx.getSharedPreferences(filename, Context.MODE_PRIVATE);
String deviceId = Settings.Secure.getString(
ctx.getContentResolver(),
Settings.Secure.ANDROID_ID);
Obfuscator o = new AESObfuscator(SALT, ctx.getPackageName(), deviceId);
op = new PreferenceObfuscator(sp, o);
// Populate with test data
op.putString("testString", "Hello world");
op.commit();
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.sergiopaniegoblanco.webrtcexampleapp", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.addpicview", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.anloq.http.test", appContext.getPackageName());
}
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.yongzheng.com.richwebproject", appContext.getPackageName());
}
@Before
public void setup() throws JSONException {
logger = mock(Logger.class);
projectId = "1";
cache = new Cache(InstrumentationRegistry.getTargetContext(), logger);
diskCache = new UserProfileCache.DiskCache(cache, executor, logger, projectId);
legacyDiskCache = new UserProfileCache.LegacyDiskCache(cache, executor, logger, projectId);
memoryCache = new ConcurrentHashMap<>();
userProfileCache = new UserProfileCache(diskCache, logger, memoryCache, legacyDiskCache);
// Test data.
userId1 = "user_1";
Map<String, Map<String, String>> experimentBucketMap1 = new ConcurrentHashMap<>();
Map<String, String> decisionMap1 = new ConcurrentHashMap<>();
decisionMap1.put("variation_id", "var_1");
experimentBucketMap1.put("exp_1", decisionMap1);
Map<String, String> decisionMap2 = new ConcurrentHashMap<>();
decisionMap2.put("variation_id", "var_2");
experimentBucketMap1.put("exp_2", decisionMap2);
userProfileMap1 = new ConcurrentHashMap<>();
userProfileMap1.put("user_id", userId1);
userProfileMap1.put("experiment_bucket_map", experimentBucketMap1);
userId2 = "user_2";
Map<String, Map<String, String>> experimentBucketMap2 = new ConcurrentHashMap<>();
Map<String, String> decisionMap3 = new ConcurrentHashMap<>();
decisionMap3.put("variation_id", "var_3");
experimentBucketMap2.put("exp_1", decisionMap3);
Map<String, String> decisionMap4 = new ConcurrentHashMap<>();
decisionMap4.put("variation_id", "var_4");
experimentBucketMap2.put("exp_2", decisionMap4);
userProfileMap2 = new ConcurrentHashMap<>();
userProfileMap2.put("user_id", userId2);
userProfileMap2.put("experiment_bucket_map", experimentBucketMap2);
}
@Test
public void testIntroductionActivityAccessibility() throws Exception {
Context targetContext = InstrumentationRegistry.getInstrumentation()
.getTargetContext();
Intent intent = new Intent(targetContext, IntroductionActivity.class);
IntroductionActivity a = introductionActivityRule.launchActivity(intent);
unlockScreen(a);
onView(withId(R.id.introductionActivityView)).perform(click());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("za.co.riggaroo.electricitymonitor", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.lqr.tinker_local", appContext.getPackageName());
}
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.journaldev.dagger2retrofitrecyclerview", appContext.getPackageName());
}
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.jsdroid.editor", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.snollidea.peppycalendarview.test", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.zhang.netty_demo", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.loonggg.weekcalendar.test", appContext.getPackageName());
}
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.luwei.checkhelper.test", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.bignerdranch.android.photogallery", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.ficat.sample", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.github.promeg.tinypinyin.android.asset.lexicons.test",
appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.tmall.wireless.viewtracker", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("it.sephiroth.android.library.rangeseekbar.test", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.android.rssreader", appContext.getPackageName());
}
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.wuwang.aavt", appContext.getPackageName());
}