@Test
public void testReleaseGarbagePermissions() throws Exception {

    Context mockContext = mock(Context.class);
    ContentResolver mockResolver = mock(ContentResolver.class);
    when(mockContext.getContentResolver()).thenReturn(mockResolver);

    final List<UriPermission> persistedPermissions = new LinkedList<>();
    when(mockResolver.getPersistedUriPermissions()).thenReturn(persistedPermissions);

    UriPermission usedPermission = mock(UriPermission.class);
    when(usedPermission.getUri()).thenReturn(newUri("content://used"));
    persistedPermissions.add(usedPermission);

    UriPermission garbagePermission = mock(UriPermission.class);
    when(garbagePermission.getUri()).thenReturn(newUri("content://garbage"));
    persistedPermissions.add(garbagePermission);

    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Iterator<UriPermission> iter = persistedPermissions.iterator();
            while (iter.hasNext()) {
                UriPermission perm = iter.next();
                if (perm.getUri() == invocation.getArgumentAt(0, Uri.class))
                    iter.remove();
            }
            return null;
        }
    }).when(mockResolver, "releasePersistableUriPermission", any(Uri.class), anyInt());

    Configuration configuration = new Configuration();
    configuration.hosts.items.add(newItemForLocation("content://used"));

    assertTrue(persistedPermissions.contains(usedPermission));
    assertTrue(persistedPermissions.contains(garbagePermission));

    new RuleDatabaseUpdateTask(mockContext, configuration, false).releaseGarbagePermissions();

    assertTrue(persistedPermissions.contains(usedPermission));
    assertFalse(persistedPermissions.contains(garbagePermission));
}