下面列出了org.mockito.Mockito#reset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void setColonEnabled() throws IOException {
TextUtilsMock.mockStatic();
NumericDisplay display = new NumericDisplay(mDevice);
final byte zero = Font.DATA[0];
final byte zeroColon = (byte) (zero | Font.COLON);
final byte[] expected = new byte[] {zero, zeroColon, zero, zero};
display.setColonEnabled(true);
assertTrue(display.getColonEnabled());
display.display("0000");
Mockito.verify(mDevice).writeRegBuffer(eq(0xc0), aryEq(expected), eq(4));
Mockito.reset(mDevice);
expected[1] = zero;
display.setColonEnabled(false);
assertFalse(display.getColonEnabled());
display.display("0000");
Mockito.verify(mDevice).writeRegBuffer(eq(0xc0), aryEq(expected), eq(4));
}
@Before
public void setUp() {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
FriendSpellApplication app
= (FriendSpellApplication) instrumentation.getTargetContext().getApplicationContext();
TestComponent component = (TestComponent) app.component();
component.inject(this);
Mockito.reset(googleApiClientBridge);
databaseApi.clear();
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.apply();
}
@Test(description = "Test update device when device modification is unsuccessful.")
public void testUpdateDeviceWithUnsuccessfulDeviceModification() throws DeviceManagementException,
DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode(),
"The response status should be 304");
Mockito.reset(this.deviceManagementProviderService);
Mockito.reset(this.deviceAccessAuthorizationService);
}
@Test
public void testSingleClientUnlockWhenCatchInterruptExceptionOnPeekLock() {
String path = ZK_PFX + "/test_interrupt_lock";
DistributedLock lock = factory.lockForClient("client");
assertFalse(lock.isLocked(path));
assertTrue(lock.lock(path));
assertTrue(lock.isLocked(path));
assertTrue(lock.isLockedByMe(path));
DistributedLock spy = Mockito.spy(lock);
// mock interruptException when peekLock only once
Mockito.doThrow(new ZkPeekLockInterruptException("mock interrupt")).doCallRealMethod().when(spy)
.peekLock(Mockito.anyString());
try {
spy.unlock(path);
fail("should throw exception");
} catch (Exception e) {
// ZkPeekLockInterruptException expected
assertTrue(e instanceof ZkPeekLockInterruptException);
}
// should release lock
Mockito.reset(spy);
assertFalse(lock.isLocked(path));
}
@Test
public void testObserveTableChange() throws Exception {
SQLite.get().enableAutomaticNotifications();
BasicTableObserver observer = Mockito.mock(BasicTableObserver.class);
Mockito.doNothing().when(observer).onTableChanged();
SQLite.get().registerObserver(TestTable.TABLE, observer);
SQLite.get().insert(TestTable.TABLE, new TestObject(5, 6, "text"));
SQLite.get().delete(TestTable.TABLE);
Thread.sleep(300);
Mockito.verify(observer, times(2)).onTableChanged();
Mockito.reset(observer);
SQLite.get().unregisterObserver(observer);
SQLite.get().insert(TestTable.TABLE, new TestObject(5, 6, "text"));
Thread.sleep(300);
Mockito.verifyNoMoreInteractions(observer);
}
@Test(description = "Test the get pending operations success scenario.")
public void testGetPendingOperationsSuccess() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier"))
.toReturn(true);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Response response = this.deviceAgentService.getPendingOperations(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertNotNull(response.getEntity(), "Response entity should not be null.");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200");
Mockito.reset(this.deviceManagementProviderService);
}
@Test
public void testSingleClientLockWhenCatchInterruptException() {
String path = ZK_PFX + "/test_interrupt_lock";
DistributedLock lock = factory.lockForClient("client");
DistributedLock spy = Mockito.spy(lock);
// mock interruptException when peekLock only once
Mockito.doThrow(new ZkPeekLockInterruptException("mock interrupt")).doCallRealMethod().when(spy)
.peekLock(Mockito.anyString());
try {
spy.lock(path);
fail("should throw exception");
} catch (Exception e) {
// ZkPeekLockInterruptException expected
assertTrue(e instanceof ZkPeekLockInterruptException);
}
// should release lock
Mockito.reset(spy);
assertFalse(lock.isLocked(path));
}
@Test(description = "Test updating device success scenario.")
public void testUpdateDeviceSuccess() throws DeviceManagementException, DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true));
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode(),
"The response status should be 202");
Mockito.reset(this.deviceManagementProviderService);
Mockito.reset(this.deviceAccessAuthorizationService);
}
@Test(description = "Test publish events with no device access authorization.")
public void testPublishEventsWithoutAuthorization() throws DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
.toReturn(this.privilegedCarbonContext);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(false);
Mockito.when(this.privilegedCarbonContext.getTenantDomain())
.thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
Map<String, Object> payload = new HashMap<>();
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(),
"The response status should be 401");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(),
"The response status should be 401");
Mockito.reset(this.deviceAccessAuthorizationService);
}
@Test(description = "Test publish events when device access authorization exception is thrown.")
public void testPublishEventsWithDeviceAccessAuthorizationException() throws DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
.toReturn(this.privilegedCarbonContext);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenThrow(new DeviceAccessAuthorizationException());
Mockito.when(this.privilegedCarbonContext.getTenantDomain())
.thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
Map<String, Object> payload = new HashMap<>();
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
List<Object> payloadList = new ArrayList<>();
Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
TEST_DEVICE_IDENTIFIER);
Assert.assertNotNull(response2, "Response should not be null");
Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500");
Mockito.reset(this.deviceAccessAuthorizationService);
}
@Before
public void setUp() throws Exception {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
MockDemoApplication app
= (MockDemoApplication) instrumentation.getTargetContext().getApplicationContext();
Injection injection = app.getInjection();
batteryReader = injection.provideBatteryReader();
Mockito.reset(batteryReader);
}
@Test(description = "Test the update device scenario when there is no enrolled device.")
public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(null);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(),
"The response status should be 404");
Mockito.reset(this.deviceManagementProviderService);
}
@Test
public void enableAlsInterrupt() throws IOException {
Vcnl4200 vcnl4200 = new Vcnl4200(mI2c);
Mockito.reset(mI2c);
vcnl4200.enableAlsInterrupt(true);
Mockito.verify(mI2c).writeRegWord(eq(Vcnl4200.REGISTER_ALS_CONF),
shortThat(hasBitsSet((short) Vcnl4200.ALS_INT_ENABLE)));
vcnl4200.enableAlsInterrupt(false);
Mockito.verify(mI2c).writeRegWord(eq(Vcnl4200.REGISTER_ALS_CONF),
shortThat(hasBitsSet((short) Vcnl4200.ALS_INT_DISABLE)));
}
@Test
void testSearchLabel() {
Mockito.reset(ontologyService);
attribute.setDescription("Standing height (m.)");
when(ontologyService.findOntologyTerms(
ontologies, ImmutableSet.of("standing", "height", "m"), 100))
.thenReturn(ontologyTerms);
Hit<OntologyTerm> result = semanticSearchService.findTags(attribute, ontologies);
assertEquals(create(standingHeight, 0.92857f), result);
}
@After
public void after() {
Mockito.reset(privateStateStorage);
}
@Test
public void testValidatePostRequest() throws Exception {
Stage.Context context =
ContextInfoCreator.createSourceContext("n", false, OnRecordError.TO_ERROR, ImmutableList.of("a"));
HttpReceiver receiver = Mockito.mock(HttpReceiverWithFragmenterWriter.class);
List id = new ArrayList<>(Arrays.asList(new CredentialValueBean("id")));
Mockito.when(receiver.getAppIds()).thenReturn(id);
Mockito.when(receiver.isApplicationIdEnabled()).thenReturn(true);
HttpReceiverServlet servlet = new HttpReceiverServlet(context, receiver, null);
servlet = Mockito.spy(servlet);
HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
// invalid AppId
Mockito.doReturn(false).when(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Assert.assertFalse(servlet.validatePostRequest(req, res));
Mockito.verify(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Mockito.verifyZeroInteractions(req);
Mockito.verifyZeroInteractions(res);
// valid AppID no compression valid receiver
Mockito.reset(req);
Mockito.reset(res);
Mockito.reset(servlet);
Mockito.doReturn(true).when(receiver).validate(Mockito.eq(req), Mockito.eq(res));
Mockito.doReturn(true).when(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Assert.assertTrue(servlet.validatePostRequest(req, res));
Mockito.verify(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Mockito.verify(req, Mockito.times(1)).getHeader(Mockito.eq(HttpConstants.X_SDC_COMPRESSION_HEADER));
Mockito.verifyZeroInteractions(res);
Mockito.verify(receiver, Mockito.times(1)).validate(Mockito.eq(req), Mockito.eq(res));
// valid AppID no compression invalid receiver
Mockito.reset(req);
Mockito.reset(res);
Mockito.reset(servlet);
Mockito.reset(receiver);
Mockito.doReturn(true).when(receiver).isApplicationIdEnabled();
Mockito.doReturn(false).when(receiver).validate(Mockito.eq(req), Mockito.eq(res));
Mockito.doReturn(true).when(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Assert.assertFalse(servlet.validatePostRequest(req, res));
Mockito.verify(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Mockito.verify(req, Mockito.times(1)).getHeader(Mockito.eq(HttpConstants.X_SDC_COMPRESSION_HEADER));
Mockito.verifyZeroInteractions(res);
Mockito.verify(receiver, Mockito.times(1)).validate(Mockito.eq(req), Mockito.eq(res));
// valid AppID with compression valid receiver
Mockito.reset(req);
Mockito.reset(res);
Mockito.reset(servlet);
Mockito.reset(receiver);
Mockito.doReturn(true).when(receiver).isApplicationIdEnabled();
Mockito.doReturn(true).when(receiver).validate(Mockito.eq(req), Mockito.eq(res));
Mockito.doReturn(true).when(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Mockito.doReturn(HttpConstants.SNAPPY_COMPRESSION).when(req).getHeader(HttpConstants.X_SDC_COMPRESSION_HEADER);
Assert.assertTrue(servlet.validatePostRequest(req, res));
Mockito.verify(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Mockito.verify(req, Mockito.times(1)).getHeader(Mockito.eq(HttpConstants.X_SDC_COMPRESSION_HEADER));
Mockito.verify(receiver, Mockito.times(1)).validate(Mockito.eq(req), Mockito.eq(res));
// valid AppID with compression valid receiver
Mockito.reset(req);
Mockito.reset(res);
Mockito.reset(servlet);
Mockito.reset(receiver);
Mockito.doReturn(true).when(receiver).isApplicationIdEnabled();
Mockito.doReturn(true).when(receiver).validate(Mockito.eq(req), Mockito.eq(res));
Mockito.doReturn(true).when(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Mockito.doReturn("invalid-compression").when(req).getHeader(HttpConstants.X_SDC_COMPRESSION_HEADER);
Assert.assertFalse(servlet.validatePostRequest(req, res));
Mockito.verify(servlet).validateAppId(Mockito.eq(req), Mockito.eq(res));
Mockito.verify(req, Mockito.times(1)).getHeader(Mockito.eq(HttpConstants.X_SDC_COMPRESSION_HEADER));
Mockito.verify(receiver, Mockito.times(0)).validate(Mockito.eq(req), Mockito.eq(res));
Mockito
.verify(res, Mockito.times(1))
.sendError(Mockito.eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), Mockito.anyString());
}
public static void reset() {
Mockito.reset(instance);
}
/**
* Test that a fault while downloading edits does not prevent future
* checkpointing
*/
@Test(timeout = 30000)
public void testEditFailureBeforeRename() throws IOException {
Configuration conf = new HdfsConfiguration();
SecondaryNameNode secondary = null;
MiniDFSCluster cluster = null;
FileSystem fs = null;
try {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes)
.build();
cluster.waitActive();
fs = cluster.getFileSystem();
secondary = startSecondaryNameNode(conf);
DFSTestUtil.createFile(fs, new Path("tmpfile0"), 1024, (short) 1, 0l);
secondary.doCheckpoint();
// Cause edit rename to fail during next checkpoint
Mockito.doThrow(new IOException("Injecting failure before edit rename"))
.when(faultInjector).beforeEditsRename();
DFSTestUtil.createFile(fs, new Path("tmpfile1"), 1024, (short) 1, 0l);
try {
secondary.doCheckpoint();
fail("Fault injection failed.");
} catch (IOException ioe) {
GenericTestUtils.assertExceptionContains(
"Injecting failure before edit rename", ioe);
}
Mockito.reset(faultInjector);
// truncate the tmp edits file to simulate a partial download
for (StorageDirectory sd : secondary.getFSImage().getStorage()
.dirIterable(NameNodeDirType.EDITS)) {
File[] tmpEdits = sd.getCurrentDir().listFiles(tmpEditsFilter);
assertTrue(
"Expected a single tmp edits file in directory " + sd.toString(),
tmpEdits.length == 1);
RandomAccessFile randFile = new RandomAccessFile(tmpEdits[0], "rw");
randFile.setLength(0);
randFile.close();
}
// Next checkpoint should succeed
secondary.doCheckpoint();
} finally {
if (secondary != null) {
secondary.shutdown();
}
if (fs != null) {
fs.close();
}
cleanup(secondary);
secondary = null;
cleanup(cluster);
cluster = null;
Mockito.reset(faultInjector);
}
}
/**
* While cleaning a directory, all the files in the directory may be deleted, but there may be
* another file added, in which case the directory shouldn't be deleted.
* @throws IOException on failure
*/
@Test
public void testCleanerDoesNotDeleteDirectoryWithLateAddedFiles() throws IOException {
Stoppable stop = new StoppableImplementation();
Configuration conf = UTIL.getConfiguration();
final Path testDir = UTIL.getDataTestDir();
final FileSystem fs = UTIL.getTestFileSystem();
String confKey = "hbase.test.cleaner.delegates";
conf.set(confKey, AlwaysDelete.class.getName());
AllValidPaths chore =
new AllValidPaths("test-file-cleaner", stop, conf, fs, testDir, confKey, POOL);
// spy on the delegate to ensure that we don't check for directories
AlwaysDelete delegate = (AlwaysDelete) chore.cleanersChain.get(0);
AlwaysDelete spy = Mockito.spy(delegate);
chore.cleanersChain.set(0, spy);
// create the directory layout in the directory to clean
final Path parent = new Path(testDir, "parent");
Path file = new Path(parent, "someFile");
fs.mkdirs(parent);
// touch a new file
fs.create(file).close();
assertTrue("Test file didn't get created.", fs.exists(file));
final Path addedFile = new Path(parent, "addedFile");
// when we attempt to delete the original file, add another file in the same directory
Mockito.doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
fs.create(addedFile).close();
CommonFSUtils.logFileSystemState(fs, testDir, LOG);
return (Boolean) invocation.callRealMethod();
}
}).when(spy).isFileDeletable(Mockito.any());
// run the chore
chore.chore();
// make sure all the directories + added file exist, but the original file is deleted
assertTrue("Added file unexpectedly deleted", fs.exists(addedFile));
assertTrue("Parent directory deleted unexpectedly", fs.exists(parent));
assertFalse("Original file unexpectedly retained", fs.exists(file));
Mockito.verify(spy, Mockito.times(1)).isFileDeletable(Mockito.any());
Mockito.reset(spy);
}
@Before
public void setup() {
Mockito.reset(blogPostRepositoryMock);
super.setup();
}