Java 类android.test.mock.MockContext 实例源码

项目:bms-clientsdk-android-core    文件:NetworkMonitorTests.java   
@Test
public void testNetworkChangeReceiver() throws Exception {
    latch = new CountDownLatch(1);

    NetworkConnectionListener listener = new NetworkConnectionListener() {
        @Override
        public void networkChanged(NetworkConnectionType newConnection) {
            latch.countDown();
        }
    };

    NetworkMonitor mockedMonitor = mock(NetworkMonitor.class);
    when(mockedMonitor.getCurrentConnectionType()).thenReturn(NetworkConnectionType.WIFI);

    Intent mockedIntent = mock(Intent.class);
    when(mockedIntent.getAction()).thenReturn(ConnectivityManager.CONNECTIVITY_ACTION);

    NetworkMonitor.NetworkChangeReceiver receiver = mockedMonitor.new NetworkChangeReceiver(listener);
    receiver.onReceive(new MockContext(), mockedIntent);

    assertTrue(latch.await(100, TimeUnit.MILLISECONDS));
}
项目:Witch-Android    文件:RecyclerViewBinderAdapterTest.java   
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    WitchTestUtils.testInit(core);
    items.add(EXISTING_BINDER_ITEM_POSITION, itemWithBinder);
    items.add(NON_EXISTING_BINDER_ITEM_POSITION, itemWithoutBinder);

    // Layout inflater stuff
    when(itemView.getTag(anyInt())).thenReturn(tagContainer);
    emptyViewHolder = new EmptyViewHolder(itemView);

    when(inflater.inflate(anyInt(), any(ViewGroup.class), anyBoolean())).thenReturn(itemView);
    MockContext context = mock(MockContext.class);
    when(context.getSystemService(eq(Service.LAYOUT_INFLATER_SERVICE))).thenReturn(inflater);
    when(parent.getContext()).thenReturn(context);

    List<RecyclerViewBinderAdapter.Binder<?>> binders = new ArrayList<>();
    binders.add(itemBinder);
    adapter = new TestRecyclerViewBinderAdapter<>(items, binders);
}
项目:espresso-macchiato    文件:EspScreenshotToolTest.java   
@Test
public void testGetFileDirFailure() {
    EspScreenshotTool espScreenshotTool = new EspScreenshotTool() {
        @Override
        protected Context getTargetContext() {
            return new MockContext() {
                @Override
                public File getFilesDir() {
                    // may happen when storage is not setup properly on emulator
                    return null;
                }
            };
        }
    };

    exception.expect(IllegalStateException.class);
    exception.expectMessage("could not find directory to store screenshot");
    espScreenshotTool.takeWithNameInternal("does not work");
}
项目:uphold-sdk-android    文件:UpholdClientTest.java   
@Test
public void beginAuthorizationShouldCallUriParse() throws Exception {
    UpholdClient.initialize(new MockSharedPreferencesContext());

    UpholdClient upholdClient = new UpholdClient();
    ArrayList<String> scopes = new ArrayList<String>() {{
        add("foo");
    }};

    PowerMockito.mockStatic(TextUtils.class);
    PowerMockito.when(TextUtils.join(" ", scopes)).thenReturn("foo");

    PowerMockito.mockStatic(Uri.class);
    upholdClient.beginAuthorization(new MockContext(), "foo", scopes, "bar");

    PowerMockito.verifyStatic();
    Uri.parse(String.format("%s/authorize/foo?scope=foo&state=bar", BuildConfig.AUTHORIZATION_SERVER_URL));
}
项目:android-job    文件:JobRequirementTest.java   
private Job setupNetworkRequirement(JobRequest.NetworkType requirement, boolean connected, int networkType, boolean roaming) {
    NetworkInfo networkInfo = mock(NetworkInfo.class);
    when(networkInfo.isConnected()).thenReturn(connected);
    when(networkInfo.isConnectedOrConnecting()).thenReturn(connected);
    when(networkInfo.getType()).thenReturn(networkType);
    when(networkInfo.isRoaming()).thenReturn(roaming);

    ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
    when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo);

    Context context = mock(MockContext.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);

    JobRequest request = mock(JobRequest.class);
    when(request.requiredNetworkType()).thenReturn(requirement);

    Job.Params params = mock(Job.Params.class);
    when(params.getRequest()).thenReturn(request);

    Job job = spy(new DummyJobs.SuccessJob());
    when(job.getParams()).thenReturn(params);
    doReturn(context).when(job).getContext();

    return job;
}
项目:android-job    文件:BaseJobManagerTest.java   
/**
 * @return A mocked context which returns a spy of {@link RuntimeEnvironment#application} in
 * {@link Context#getApplicationContext()}.
 */
public static Context createMockContext() {
    // otherwise the JobScheduler isn't supported we check if the service is enable
    // Robolectric doesn't parse services from the manifest, see https://github.com/robolectric/robolectric/issues/416
    PackageManager packageManager = mock(PackageManager.class);
    when(packageManager.queryBroadcastReceivers(any(Intent.class), anyInt())).thenReturn(Collections.singletonList(new ResolveInfo()));

    ResolveInfo resolveInfo = new ResolveInfo();
    resolveInfo.serviceInfo = new ServiceInfo();
    resolveInfo.serviceInfo.permission = "android.permission.BIND_JOB_SERVICE";
    when(packageManager.queryIntentServices(any(Intent.class), anyInt())).thenReturn(Collections.singletonList(resolveInfo));

    Context context = spy(RuntimeEnvironment.application);
    when(context.getPackageManager()).thenReturn(packageManager);
    when(context.getApplicationContext()).thenReturn(context);

    Context mockContext = mock(MockContext.class);
    when(mockContext.getApplicationContext()).thenReturn(context);
    return mockContext;
}
项目:android-job    文件:DeviceTest.java   
@Test
public void testNetworkStateMeteredNotRoaming() {
    NetworkInfo networkInfo = mock(NetworkInfo.class);
    when(networkInfo.isConnected()).thenReturn(true);
    when(networkInfo.isConnectedOrConnecting()).thenReturn(true);
    when(networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
    when(networkInfo.isRoaming()).thenReturn(false);

    ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
    when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo);

    Context context = mock(MockContext.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);

    assertThat(Device.getNetworkType(context)).isEqualTo(JobRequest.NetworkType.NOT_ROAMING);
}
项目:android-job    文件:DeviceTest.java   
@Test
public void testNetworkStateRoaming() {
    NetworkInfo networkInfo = mock(NetworkInfo.class);
    when(networkInfo.isConnected()).thenReturn(true);
    when(networkInfo.isConnectedOrConnecting()).thenReturn(true);
    when(networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_MOBILE);
    when(networkInfo.isRoaming()).thenReturn(true);

    ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
    when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo);

    Context context = mock(MockContext.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);

    assertThat(Device.getNetworkType(context)).isEqualTo(JobRequest.NetworkType.CONNECTED);
}
项目:android-job    文件:DeviceTest.java   
@Test
public void testNetworkStateWifiAndMobile() {
    NetworkInfo networkInfo = mock(NetworkInfo.class);
    when(networkInfo.isConnected()).thenReturn(true);
    when(networkInfo.isConnectedOrConnecting()).thenReturn(true);
    when(networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_WIFI);
    when(networkInfo.isRoaming()).thenReturn(false);

    ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
    when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo);

    Context context = mock(MockContext.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);

    assertThat(Device.getNetworkType(context)).isEqualTo(JobRequest.NetworkType.UNMETERED);
}
项目:android-job    文件:DeviceTest.java   
@Test
public void testNetworkStateWifiAndRoaming() {
    NetworkInfo networkInfo = mock(NetworkInfo.class);
    when(networkInfo.isConnected()).thenReturn(true);
    when(networkInfo.isConnectedOrConnecting()).thenReturn(true);
    when(networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_WIFI);
    when(networkInfo.isRoaming()).thenReturn(true);

    ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
    when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo);

    Context context = mock(MockContext.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);

    assertThat(Device.getNetworkType(context)).isEqualTo(JobRequest.NetworkType.UNMETERED);
}
项目:bms-clientsdk-android-core    文件:NetworkMonitorTests.java   
@Test
public void testStartMonitoringNetworkChanges() throws Exception {
    latch = new CountDownLatch(1);

    class TestContext extends MockContext {
        @Override
        public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
            assertTrue(receiver instanceof NetworkMonitor.NetworkChangeReceiver);
            latch.countDown();
            return null;
        }
    }

    Context context = new TestContext();
    NetworkMonitor networkMonitor = new NetworkMonitor(context, getNetworkListener());
    networkMonitor.startMonitoringNetworkChanges();

    assertTrue(latch.await(100, TimeUnit.MILLISECONDS));
}
项目:bms-clientsdk-android-core    文件:NetworkMonitorTests.java   
@Test
public void testStopMonitoringNetworkChanges() throws Exception {
    latch = new CountDownLatch(1);

    class TestContext extends MockContext {
        @Override
        public void unregisterReceiver(BroadcastReceiver receiver) {
            assertTrue(receiver instanceof NetworkMonitor.NetworkChangeReceiver);
            latch.countDown();
        }
    }

    Context context = new TestContext();
    NetworkMonitor networkMonitor = new NetworkMonitor(context, getNetworkListener());
    networkMonitor.startMonitoringNetworkChanges();
    networkMonitor.stopMonitoringNetworkChanges();

    assertTrue(latch.await(100, TimeUnit.MILLISECONDS));
}
项目:bms-clientsdk-android-core    文件:NetworkMonitorTests.java   
@Test
public void testStopMonitoringNetworkChangesWithNullListener() {

    class TestContext extends MockContext {
        @Override
        public void unregisterReceiver(BroadcastReceiver receiver) {
            fail("Should not have a receiver without a NetworkChangeListener given to NetworkMonitor.");
        }
    }

    // Test with null Listener
    Context context = new TestContext();
    NetworkMonitor networkMonitor = new NetworkMonitor(context, null);
    networkMonitor.startMonitoringNetworkChanges();
    networkMonitor.stopMonitoringNetworkChanges();

    // Test misuse of the API
    context = new TestContext();
    networkMonitor = new NetworkMonitor(context, null);
    networkMonitor.stopMonitoringNetworkChanges();
    networkMonitor.stopMonitoringNetworkChanges();
    networkMonitor.stopMonitoringNetworkChanges();
}
项目:arca-android    文件:SimpleOperationTest.java   
public void testSimpleOperationNotifiesChangeOnSuccess() {
    final AssertionLatch latch = new AssertionLatch(1);
    final MockContext context = new MockContext() {
        @Override
        public ContentResolver getContentResolver() {
            return new MockContentResolver() {
                @Override
                public void notifyChange(final Uri u, final ContentObserver o) {
                    latch.countDown();
                }
            };
        }
    };
    final TestSimpleOperation operation = new TestSimpleOperation(Uri.EMPTY);
    operation.onSuccess(context, null);
    latch.assertComplete();
}
项目:LucaHome-AndroidApplication    文件:JsonConverterTest.java   
@Test
public void JsonDataToBirthdayConverterTest() throws Exception {
    String response = "{\"Data\":[{\"Birthday\":{\"Id\":0,\"Name\":\"Jonas Schubert\",\"Group\":\"Family\",\"RemindMe\":0,\"SentMail\":0,\"Date\":{\"Day\":2,\"Month\":1,\"Year\":1990}}},{\"Birthday\":{\"Id\":1,\"Name\":\"Artur Rychter\",\"Group\":\"Friends\",\"RemindMe\":1,\"SentMail\":0,\"Date\":{\"Day\":21,\"Month\":3,\"Year\":1990}}}]} ";
    MockContext mockContext = new MockContext();

    SerializableList<LucaBirthday> birthdayList = JsonDataToBirthdayConverter.getInstance().GetList(response, mockContext);

    assertNotNull(birthdayList);
    assertEquals(birthdayList.getSize(), 2);
    assertEquals(birthdayList.getValue(0).GetName(), "Jonas Schubert");
}
项目:swipe-maker    文件:SwipeLayoutTest.java   
@Before
public void setup() {
    swipeLayout = new SwipeLayout(new MockContext());
    orientationStrategy = mock(OrientationStrategy.class);
    OrientationStrategyFactory orientationStrategyFactory = new OrientationStrategyFactory() {
        @Override
        public OrientationStrategy make(View view) {
            return orientationStrategy;
        }
    };
    swipeLayout.setOrientation(orientationStrategyFactory);
    verifyNoMoreInteractions(orientationStrategy);
}
项目:LucaHome-AndroidApplication    文件:JsonConverterTest.java   
@Test
public void JsonDataToBirthdayConverterTest() throws Exception {
    String response = "{\"Data\":[{\"Birthday\":{\"Id\":0,\"Name\":\"Jonas Schubert\",\"Group\":\"Family\",\"RemindMe\":0,\"SentMail\":0,\"Date\":{\"Day\":2,\"Month\":1,\"Year\":1990}}},{\"Birthday\":{\"Id\":1,\"Name\":\"Artur Rychter\",\"Group\":\"Friends\",\"RemindMe\":1,\"SentMail\":0,\"Date\":{\"Day\":21,\"Month\":3,\"Year\":1990}}}]} ";
    MockContext mockContext = new MockContext();

    SerializableList<LucaBirthday> birthdayList = JsonDataToBirthdayConverter.getInstance().GetList(response, mockContext);

    assertNotNull(birthdayList);
    assertEquals(birthdayList.getSize(), 2);
    assertEquals(birthdayList.getValue(0).GetName(), "Jonas Schubert");
}
项目:unity-ads-android    文件:PackageManagerTest.java   
@Before
public void setup() {
    ClientProperties.setApplicationContext(new MockContext() {
        @Override
        public PackageManager getPackageManager() {
            return new TestPackageManager();
        }
    });
}
项目:fingerpoetry-android    文件:ApiTest.java   
@Test
public void login() throws IOException {
    Context context = new MockContext();
    Observable<ApiResult<LoginData>> observable= bookRetrofit.getAccountApi().login("18301441595", "123456");
    observable.observeOn(Schedulers.immediate())
            .subscribeOn(Schedulers.immediate())
            .subscribe(observer);
}
项目:ironbeast-android    文件:IronBeastTest.java   
@Test public void testGetInstance() {
    MockContext context = mock(MockContext.class);
    IronBeast ironBeast = IronBeast.getInstance(context);

    IronBeastTracker tracker1 = ironBeast.newTracker("token1");
    IronBeastTracker tracker2 = ironBeast.newTracker("token1");
    assertTrue("should not initialized new tracker with the same token", tracker1 == tracker2);
    IronBeastTracker tracker3 = ironBeast.newTracker("token2");
    assertTrue("should initialized new tracker", tracker1 != tracker3 || tracker2 != tracker3);
}
项目:digits-android    文件:ContactsClientTests.java   
@Before
public void setUp() throws Exception {
    activityClassManagerFactory = new ActivityClassManagerFactory();
    context = mock(MockContext.class);
    callback = mock(ContactsCallback.class);
    prefManager = mock(ContactsPreferenceManager.class);
    digitsEventCollector = mock(DigitsEventCollector.class);
    callbackCaptor = ArgumentCaptor.forClass(ContactsClient.FoundContactsCallbackWrapper.class);
    fabric = mock(Fabric.class);
    activity = mock(Activity.class);
    intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
    sandboxConfig = mock(SandboxConfig.class);
    when(digits.getContext()).thenReturn(context);
    when(context.getPackageName()).thenReturn(getClass().getPackage().toString());
    when(digits.getActivityClassManager()).thenReturn(new ActivityClassManagerImp());
    when(digits.getFabric()).thenReturn(fabric);
    when(fabric.getCurrentActivity()).thenReturn(activity);
    when(activity.isFinishing()).thenReturn(false);
    when(sandboxConfig.isMode(SandboxConfig.Mode.DEFAULT)).thenReturn(false);

    sdkService = mock(ApiInterface.class);
    apiClientManager = mock(DigitsApiClientManager.class);
    when(apiClientManager.getService()).thenReturn(sdkService);

    contactsClient = new ContactsClient(digits, apiClientManager, prefManager,
            activityClassManagerFactory, sandboxConfig, digitsEventCollector);

    activityComponent = new ComponentName(context, ContactsActivity.class.getName());
    serviceComponent = new ComponentName(context, ContactsUploadService.class.getName());
}
项目:digits-android    文件:ContactsControllerTests.java   
@Before
public void setUp() throws Exception {


    controller = new ContactsControllerImpl();
    context = mock(MockContext.class);
    intentCaptor = ArgumentCaptor.forClass(Intent.class);

    when(context.getPackageName()).thenReturn(ContactsUploadService.class.getPackage()
            .toString());
}
项目:digits-android    文件:ContactsHelperTests.java   
@Before
public void setUp() throws Exception {
    context = mock(MockContext.class);
    contentResolver = mock(ContentResolver.class);
    cursor = createCursor();

    when(contentResolver.query(any(Uri.class), any(String[].class), any(String.class), any
            (String[].class), any(String.class))).thenReturn(cursor);
    when(context.getContentResolver()).thenReturn(contentResolver);
}
项目:android-job    文件:JobManagerCreateTest.java   
private Context mockContext() {
    SharedPreferences preferences = mock(SharedPreferences.class);
    when(preferences.getStringSet(anyString(), ArgumentMatchers.<String>anySet())).thenReturn(new HashSet<String>());

    Context context = mock(MockContext.class);
    when(context.getApplicationContext()).thenReturn(context);
    when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(preferences);
    return context;
}
项目:android-job    文件:DeviceTest.java   
@Test
public void testNetworkStateNotConnectedWithNullNetworkInfo() {
    ConnectivityManager connectivityManager = mock(ConnectivityManager.class);

    Context context = mock(MockContext.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);

    assertThat(Device.getNetworkType(context)).isEqualTo(JobRequest.NetworkType.ANY);
}
项目:android-job    文件:DeviceTest.java   
@Test
public void testNetworkStateNotConnected() {
    NetworkInfo networkInfo = mock(NetworkInfo.class);
    when(networkInfo.isConnected()).thenReturn(false);
    when(networkInfo.isConnectedOrConnecting()).thenReturn(false);

    ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
    when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo);

    Context context = mock(MockContext.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);

    assertThat(Device.getNetworkType(context)).isEqualTo(JobRequest.NetworkType.ANY);
}
项目:android-job    文件:DeviceTest.java   
@Test
public void testNetworkStateUnmeteredWifi() {
    NetworkInfo networkInfo = mock(NetworkInfo.class);
    when(networkInfo.isConnected()).thenReturn(true);
    when(networkInfo.isConnectedOrConnecting()).thenReturn(true);
    when(networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_WIFI);

    ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
    when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo);

    Context context = mock(MockContext.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);

    assertThat(Device.getNetworkType(context)).isEqualTo(JobRequest.NetworkType.UNMETERED);
}
项目:bms-clientsdk-android-core    文件:NetworkMonitorTests.java   
@Test
public void testConstructor() {
    NetworkMonitor networkMonitor = new NetworkMonitor(new MockContext(), getNetworkListener());
    assertNotNull(networkMonitor.getNetworkReceiver());

    networkMonitor = new NetworkMonitor(new MockContext(), null);
    assertNull(networkMonitor.getNetworkReceiver());
}
项目:bms-clientsdk-android-core    文件:NetworkMonitorTests.java   
@Test
public void testStartMonitoringNetworkChangesWithNullListener() {

    class TestContext extends MockContext {
        @Override
        public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
            fail("Should not have registered a receiver without a NetworkChangeListener given to NetworkMonitor.");
            return null;
        }
    }

    Context context = new TestContext();
    NetworkMonitor networkMonitor = new NetworkMonitor(context, null);
    networkMonitor.startMonitoringNetworkChanges();
}
项目:arca-android    文件:SimpleOperationTest.java   
public void testSimpleOperationInsertsDataOnSuccess() throws Exception {
    final AssertionLatch latch = new AssertionLatch(1);
    final MockContext context = new MockContextWithProvider(new MockContentProvider() {
        @Override
        public int bulkInsert(Uri u, ContentValues[] v) {
            latch.countDown();
            assertEquals(URI, u);
            return 0;
        }
    });
    final TestSimpleOperation operation = new TestSimpleOperation(URI);
    operation.onPostExecute(context, new ContentValues[0]);
    latch.assertComplete();
}
项目:what-stored-in-a-mobile-device-android    文件:UniqueIdentifierTest.java   
@Override
protected void setUp() throws Exception {
    super.setUp();
    TestSetup.setupMockito(this);
    Context mockContext = mock(MockContext.class);
    WifiManager wm = mock(WifiManager.class);
    when(mockContext.getSystemService(Context.WIFI_SERVICE)).thenReturn(wm);
    WifiInfo info = mock(WifiInfo.class);
    when(info.getMacAddress())
            .thenReturn("1")
            .thenReturn("2");
    when(wm.getConnectionInfo()).thenReturn(info);
    identifier = new UniqueIdentifier(mockContext);
}
项目:loopy-sdk-android    文件:LoopyTest.java   
public void testShareFromIntent() throws PackageManager.NameNotFoundException {

        final String appName = "foobar_app";
        final Item item = Mockito.mock(Item.class);
        final MockAppDataCache appDataCache = Mockito.mock(MockAppDataCache.class);
        final PackageManager packageManager = Mockito.mock(PackageManager.class);
        final ActivityInfo activityInfo = Mockito.mock(ActivityInfo.class);
        final Context context = Mockito.mock(MockContext.class);
        final ComponentName cn = new ComponentName("foo", "bar");
        final Intent intent = new Intent();
        final MockLoopy loopy = Mockito.mock(MockLoopy.class);
        intent.setComponent(cn);

        MockAppDataCache.setInstance(appDataCache);

        Mockito.when(appDataCache.getAppLabel("foo", "bar")).thenReturn(null);
        Mockito.when(context.getPackageManager()).thenReturn(packageManager);
        Mockito.when(packageManager.getActivityInfo(cn, 0)).thenReturn(activityInfo);
        Mockito.when(activityInfo.loadLabel(packageManager)).thenReturn(appName);

        Mockito.doCallRealMethod().when(loopy).shareFromIntent(context, item, intent);

        loopy.shareFromIntent(context, item, intent);

        Mockito.verify(loopy).share(item, appName, null);

    }
项目:loopy-sdk-android    文件:AppUtilsTest.java   
public void testHasAndPermission() {

        Context trueContext = Mockito.mock(MockContext.class);
        Context falseContext = Mockito.mock(MockContext.class);

        Mockito.when(trueContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_GRANTED);
        Mockito.when(falseContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_DENIED);

        assertTrue(AppUtils.getInstance().hasAndPermission(trueContext, "foo", "bar"));
        assertFalse(AppUtils.getInstance().hasAndPermission(falseContext, "foo", "bar"));
    }
项目:loopy-sdk-android    文件:AppUtilsTest.java   
public void testListAppsForType() {

        final Intent intent = new Intent();

        PackageManager pm = Mockito.mock(PackageManager.class);
        Context context = Mockito.mock(MockContext.class);

        ResolveInfo foo = Mockito.mock(ResolveInfo.class);
        ResolveInfo bar = Mockito.mock(ResolveInfo.class);

        List<ResolveInfo> infos = Arrays.asList(foo, bar);

        Mockito.when(foo.loadLabel(pm)).thenReturn("foo");
        Mockito.when(bar.loadLabel(pm)).thenReturn("bar");
        Mockito.when(context.getPackageManager()).thenReturn(pm);
        Mockito.when(pm.queryIntentActivities(intent, 0)).thenReturn(infos);

        MockAppUtils appUtils = new MockAppUtils() {
            @Override
            public Intent getSendIntent() {
                return intent;
            }
        };

        List<ResolveInfo> apps = appUtils.listAppsForType(context, "foobar");

        assertNotNull(apps);
        assertEquals(infos.size(), apps.size());

        // Check sorted
        assertSame(bar, apps.get(0));
        assertSame(foo, apps.get(1));

        Mockito.verify(pm).queryIntentActivities(intent, 0);
    }
项目:eBread    文件:VolleyRequestTest.java   
@Before
public void createVolleyRequest() {
    context = new MockContext();
    volleyRequest = new VolleyRequest();
}
项目:science-journal    文件:MockRecorderService.java   
@Override
public Context getApplicationContext() {
    return new MockContext();
}
项目:fdroid    文件:ProviderTestCase2MockContext.java   
/**
 * <p>
 *      Creates a new content provider of the same type as that passed to the test case class,
 *      with an authority name set to the authority parameter, and using an SQLite database as
 *      the underlying data source. The SQL statement parameter is used to create the database.
 *      This method also creates a new {@link MockContentResolver} and adds the provider to it.
 * </p>
 * <p>
 *      Both the new provider and the new resolver are put into an {@link IsolatedContext}
 *      that uses the targetContext parameter for file operations and a {@link MockContext}
 *      for everything else. The IsolatedContext prepends the filenamePrefix parameter to
 *      file, database, and directory names.
 * </p>
 * <p>
 *      This is a convenience method for creating a "mock" provider that can contain test data.
 * </p>
 *
 * @param targetContext The context to use as the basis of the IsolatedContext
 * @param filenamePrefix A string that is prepended to file, database, and directory names
 * @param providerClass The type of the provider being tested
 * @param authority The authority string to associated with the test provider
 * @param databaseName The name assigned to the database
 * @param databaseVersion The version assigned to the database
 * @param sql A string containing the SQL statements that are needed to create the desired
 * database and its tables. The format is the same as that generated by the
 * <a href="http://www.sqlite.org/sqlite.html">sqlite3</a> tool's <code>.dump</code> command.
 * @return ContentResolver A new {@link MockContentResolver} linked to the provider
 *
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public static <T extends ContentProvider> ContentResolver newResolverWithContentProviderFromSql(
        Context targetContext, String filenamePrefix, Class<T> providerClass, String authority,
        String databaseName, int databaseVersion, String sql)
        throws IllegalAccessException, InstantiationException {
    MockContentResolver resolver = new MockContentResolver();
    RenamingDelegatingContext targetContextWrapper = new RenamingDelegatingContext(
            new MockContext(), // The context that most methods are delegated to
            targetContext, // The context that file methods are delegated to
            filenamePrefix);
    Context context = new IsolatedContext(resolver, targetContextWrapper);
    DatabaseUtils.createDbFromSqlStatements(context, databaseName, databaseVersion, sql);

    T provider = providerClass.newInstance();
    provider.attachInfo(context, null);
    resolver.addProvider(authority, provider);

    return resolver;
}
项目:AppHub    文件:ProviderTestCase2MockContext.java   
/**
 * <p>
 *      Creates a new content provider of the same type as that passed to the test case class,
 *      with an authority name set to the authority parameter, and using an SQLite database as
 *      the underlying data source. The SQL statement parameter is used to create the database.
 *      This method also creates a new {@link MockContentResolver} and adds the provider to it.
 * </p>
 * <p>
 *      Both the new provider and the new resolver are put into an {@link IsolatedContext}
 *      that uses the targetContext parameter for file operations and a {@link MockContext}
 *      for everything else. The IsolatedContext prepends the filenamePrefix parameter to
 *      file, database, and directory names.
 * </p>
 * <p>
 *      This is a convenience method for creating a "mock" provider that can contain test data.
 * </p>
 *
 * @param targetContext The context to use as the basis of the IsolatedContext
 * @param filenamePrefix A string that is prepended to file, database, and directory names
 * @param providerClass The type of the provider being tested
 * @param authority The authority string to associated with the test provider
 * @param databaseName The name assigned to the database
 * @param databaseVersion The version assigned to the database
 * @param sql A string containing the SQL statements that are needed to create the desired
 * database and its tables. The format is the same as that generated by the
 * <a href="http://www.sqlite.org/sqlite.html">sqlite3</a> tool's <code>.dump</code> command.
 * @return ContentResolver A new {@link MockContentResolver} linked to the provider
 *
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public static <T extends ContentProvider> ContentResolver newResolverWithContentProviderFromSql(
        Context targetContext, String filenamePrefix, Class<T> providerClass, String authority,
        String databaseName, int databaseVersion, String sql)
        throws IllegalAccessException, InstantiationException {
    MockContentResolver resolver = new MockContentResolver();
    RenamingDelegatingContext targetContextWrapper = new RenamingDelegatingContext(
            new MockContext(), // The context that most methods are delegated to
            targetContext, // The context that file methods are delegated to
            filenamePrefix);
    Context context = new IsolatedContext(resolver, targetContextWrapper);
    DatabaseUtils.createDbFromSqlStatements(context, databaseName, databaseVersion, sql);

    T provider = providerClass.newInstance();
    provider.attachInfo(context, null);
    resolver.addProvider(authority, provider);

    return resolver;
}
项目:digits-android    文件:LoginOrSignupComposerTest.java   
@Before
public void setUp() throws Exception {
    context = mock(MockContext.class);
    digitsClient = mock(DigitsClient.class);
    sessionManager = mock(SessionManager.class);
    resultReceiver = mock(ResultReceiver.class);
    activityClassManager = mock(ActivityClassManager.class);
    callbackCaptor = ArgumentCaptor.forClass(Callback.class);
    loginCodeActivity = LoginCodeActivity.class;
    confirmationCodeActivity = ConfirmationCodeActivity.class;
    retrofitError = mock(RetrofitError.class);
    resources = mock(Resources.class);

    authConfig = new AuthConfig();
    authConfig.isEmailEnabled = true;
    authConfig.isVoiceEnabled = true;

    authResponse = new AuthResponse();
    authResponse.requestId = FAKE_REQUEST_ID;
    authResponse.userId = FAKE_USER_ID;
    authResponse.normalizedPhoneNumber = PHONE_WITH_COUNTRY_CODE;
    authResponse.authConfig = authConfig;

    deviceRegistrationResponse = new DeviceRegistrationResponse();
    deviceRegistrationResponse.authConfig = authConfig;
    deviceRegistrationResponse.normalizedPhoneNumber = PHONE_WITH_COUNTRY_CODE;
    digitsEventDetailsBuilder = new DigitsEventDetailsBuilder()
            .withAuthStartTime(System.currentTimeMillis());

    when(activityClassManager.getLoginCodeActivity()).thenReturn(loginCodeActivity);
    when(activityClassManager.getConfirmationActivity()).thenReturn(confirmationCodeActivity);
    when(context.getPackageName()).thenReturn(getClass().getPackage().toString());
    when(retrofitError.isNetworkError()).thenReturn(false);
    when(context.getResources()).thenReturn(resources);
    when(resources.getString(R.string.dgts__try_again)).thenReturn("try again");

    couldNotAuthenticateException = new MockDigitsApiException
            (new ApiError("Message", TwitterApiErrorConstants.COULD_NOT_AUTHENTICATE), null,
                    retrofitError);

    userIsNotSdkUserException = new MockDigitsApiException
            (new ApiError("Message", TwitterApiErrorConstants.USER_IS_NOT_SDK_USER), null,
                    retrofitError);

    registrationRateExceededException = new MockDigitsApiException
            (new ApiError("Message",
                    TwitterApiErrorConstants.DEVICE_REGISTRATION_RATE_EXCEEDED), null,
                    retrofitError);

    guestAuthException = new MockDigitsApiException
            (new ApiError("Message",
                    TwitterApiConstants.Errors.GUEST_AUTH_ERROR_CODE), null,
                    retrofitError);

}
项目:digits-android    文件:DigitsClientTests.java   
@Before
public void setUp() throws Exception {
    digits = mock(Digits.class);
    digitsUserAgent = new DigitsUserAgent("digitsVersion", "androidVersion", "appName");
    sessionManager = mock(SessionManager.class);
    twitterCore = mock(TwitterCore.class);
    twitterAuthConfig = new TwitterAuthConfig(TestConstants.CONSUMER_KEY,
            TestConstants.CONSUMER_SECRET);
    digitsApiClient = mock(DigitsApiClient.class);
    service = mock(ApiInterface.class);
    executorService = mock(ExecutorService.class);
    context = mock(MockContext.class);
    controller = mock(DigitsController.class);
    callback = mock(AuthCallback.class);
    digitsEventCollector = mock(DigitsEventCollector.class);
    fabric = mock(Fabric.class);
    activity = mock(Activity.class);
    loginResultReceiver = new LoginResultReceiver(new WeakAuthCallback(callback),
            sessionManager, mock(DigitsEventCollector.class));
    authRequestQueue = createRequestQueue();
    userSession = DigitsSession.create(TestConstants.DIGITS_USER, TestConstants.PHONE);
    guestSession = DigitsSession.create(TestConstants.LOGGED_OUT_USER, "");
    digitsEventDetailsBuilder = new DigitsEventDetailsBuilder()
            .withAuthStartTime(System.currentTimeMillis())
            .withCountry("US")
            .withLanguage("en");
    detailsArgumentCaptor = ArgumentCaptor.forClass(DigitsEventDetails.class);

    when(digitsApiClient.getService()).thenReturn(service);
    when(digits.getContext()).thenReturn(context);
    when(digits.getAuthConfig()).thenReturn(twitterAuthConfig);
    when(twitterCore.getSSLSocketFactory()).thenReturn(mock(SSLSocketFactory.class));
    when(digits.getExecutorService()).thenReturn(mock(ExecutorService.class));
    when(digits.getActivityClassManager()).thenReturn(new ActivityClassManagerImp());
    when(digits.getDigitsEventCollector()).thenReturn(digitsEventCollector);
    when(digits.getFabric()).thenReturn(fabric);
    when(digits.getVersion()).thenReturn(ANY_VERSION);
    when(fabric.getCurrentActivity()).thenReturn(activity);
    when(context.getPackageName()).thenReturn(getClass().getPackage().toString());
    when(activity.getPackageName()).thenReturn(getClass().getPackage().toString());
    when(activity.isFinishing()).thenReturn(false);
    when(controller.getErrors()).thenReturn(mock(ErrorCodes.class));
    apiClientManager = mock(DigitsApiClientManager.class);
    when(apiClientManager.getService()).thenReturn(service);
    when(apiClientManager.getApiClient()).thenReturn(digitsApiClient);

    digitsClient = new DigitsClient(digits, sessionManager, apiClientManager,
            authRequestQueue, digitsEventCollector, sandboxConfig) {
        @Override
        LoginResultReceiver createResultReceiver(AuthCallback callback) {
            return loginResultReceiver;
        }
    };
}