use of org.mockito.stubbing.Answer in project mobile-center-sdk-android by Microsoft.
the class CrashesTest method setUp.
@Before
public void setUp() throws Exception {
/* Mock handler for asynchronous Crashes */
final Handler mockHandler = mock(Handler.class);
whenNew(Handler.class).withParameterTypes(Looper.class).withArguments(any(Looper.class)).thenAnswer(new Answer<Handler>() {
@Override
public Handler answer(InvocationOnMock invocation) throws Throwable {
mMockLooper = mock(Looper.class);
when(mockHandler.getLooper()).thenReturn(mMockLooper);
return mockHandler;
}
});
when(mockHandler.post(any(Runnable.class))).then(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
((Runnable) invocation.getArguments()[0]).run();
return true;
}
});
Thread.setDefaultUncaughtExceptionHandler(null);
Crashes.unsetInstance();
mockStatic(SystemClock.class);
mockStatic(StorageHelper.InternalStorage.class);
mockStatic(StorageHelper.PreferencesStorage.class);
mockStatic(MobileCenterLog.class);
when(SystemClock.elapsedRealtime()).thenReturn(System.currentTimeMillis());
mockStatic(MobileCenter.class);
Mockito.when(MobileCenter.isEnabled()).thenReturn(true);
when(StorageHelper.PreferencesStorage.getBoolean(CRASHES_ENABLED_KEY, true)).thenReturn(true);
/* Then simulate further changes to state. */
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
/* Whenever the new state is persisted, make further calls return the new state. */
boolean enabled = (Boolean) invocation.getArguments()[1];
when(StorageHelper.PreferencesStorage.getBoolean(CRASHES_ENABLED_KEY, true)).thenReturn(enabled);
return null;
}
}).when(StorageHelper.PreferencesStorage.class);
StorageHelper.PreferencesStorage.putBoolean(eq(CRASHES_ENABLED_KEY), anyBoolean());
mockStatic(HandlerUtils.class);
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
((Runnable) invocation.getArguments()[0]).run();
return null;
}
}).when(HandlerUtils.class);
HandlerUtils.runOnUiThread(any(Runnable.class));
mErrorLog = ErrorLogHelper.createErrorLog(mock(Context.class), Thread.currentThread(), new RuntimeException(), Thread.getAllStackTraces(), 0, true);
}
use of org.mockito.stubbing.Answer in project ORCID-Source by ORCID.
the class ManageProfileControllerTest method initMocks.
@Before
public void initMocks() throws Exception {
controller = new ManageProfileController();
MockitoAnnotations.initMocks(this);
SecurityContextHolder.getContext().setAuthentication(getAuthentication(USER_ORCID));
TargetProxyHelper.injectIntoProxy(controller, "profileEntityCacheManager", mockProfileEntityCacheManager);
TargetProxyHelper.injectIntoProxy(controller, "encryptionManager", mockEncryptionManager);
TargetProxyHelper.injectIntoProxy(controller, "emailManager", mockEmailManager);
TargetProxyHelper.injectIntoProxy(controller, "localeManager", mockLocaleManager);
TargetProxyHelper.injectIntoProxy(controller, "profileEntityManager", mockProfileEntityManager);
TargetProxyHelper.injectIntoProxy(controller, "givenPermissionToManager", mockGivenPermissionToManager);
TargetProxyHelper.injectIntoProxy(controller, "orcidSecurityManager", mockOrcidSecurityManager);
when(mockOrcidSecurityManager.isPasswordConfirmationRequired()).thenReturn(true);
when(mockEncryptionManager.hashMatches(Mockito.anyString(), Mockito.anyString())).thenReturn(true);
when(mockEncryptionManager.hashMatches(Mockito.eq("invalid password"), Mockito.anyString())).thenReturn(false);
when(mockProfileEntityManager.deprecateProfile(Mockito.anyString(), Mockito.anyString())).thenReturn(false);
when(mockProfileEntityManager.deprecateProfile(Mockito.eq(DEPRECATED_USER_ORCID), Mockito.eq(USER_ORCID))).thenReturn(true);
when(mockLocaleManager.resolveMessage(Mockito.anyString(), Mockito.any())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return invocation.getArgument(0);
}
});
when(mockProfileEntityCacheManager.retrieve(Mockito.anyString())).then(new Answer<ProfileEntity>() {
@Override
public ProfileEntity answer(InvocationOnMock invocation) throws Throwable {
ProfileEntity entity = new ProfileEntity();
entity.setId(invocation.getArgument(0));
Set<GivenPermissionToEntity> givenPermissionTo = new HashSet<GivenPermissionToEntity>();
IntStream.range(0, 2).forEachOrdered(i -> {
GivenPermissionToEntity e1 = new GivenPermissionToEntity();
e1.setId(Long.valueOf(i));
Date now = new Date();
e1.setApprovalDate(now);
e1.setDateCreated(now);
e1.setGiver(invocation.getArgument(0));
ProfileSummaryEntity ps = new ProfileSummaryEntity();
RecordNameEntity recordName = new RecordNameEntity();
recordName.setVisibility(Visibility.PUBLIC);
if (i == 0) {
ps.setId("0000-0000-0000-0004");
recordName.setCreditName("Credit Name");
} else {
ps.setId("0000-0000-0000-0005");
recordName.setFamilyName("Family Name");
recordName.setGivenNames("Given Names");
}
ps.setRecordNameEntity(recordName);
e1.setReceiver(ps);
givenPermissionTo.add(e1);
});
entity.setGivenPermissionTo(givenPermissionTo);
EmailEntity email1 = new EmailEntity();
email1.setId(invocation.getArgument(0) + "_1@test.orcid.org");
email1.setVerified(true);
email1.setCurrent(true);
email1.setDateCreated(new Date());
email1.setLastModified(new Date());
email1.setPrimary(true);
email1.setVisibility(Visibility.PUBLIC);
EmailEntity email2 = new EmailEntity();
email2.setId(invocation.getArgument(0) + "_2@test.orcid.org");
email2.setVerified(true);
email2.setCurrent(false);
email2.setDateCreated(new Date());
email2.setLastModified(new Date());
email2.setPrimary(false);
email2.setVisibility(Visibility.PUBLIC);
Set<EmailEntity> emails = new HashSet<EmailEntity>();
emails.add(email1);
emails.add(email2);
entity.setEmails(emails);
entity.setRecordNameEntity(getRecordName(invocation.getArgument(0)));
entity.setEncryptedPassword("password");
return entity;
}
});
when(mockEmailManager.getEmails(Mockito.anyString(), Mockito.anyLong())).thenAnswer(new Answer<Emails>() {
@Override
public Emails answer(InvocationOnMock invocation) throws Throwable {
Emails emails = new Emails();
Email email1 = new Email();
email1.setEmail(invocation.getArgument(0) + "_1@test.orcid.org");
email1.setVisibility(Visibility.PUBLIC);
emails.getEmails().add(email1);
Email email2 = new Email();
email2.setEmail(invocation.getArgument(0) + "_2@test.orcid.org");
email2.setVisibility(Visibility.PUBLIC);
emails.getEmails().add(email2);
return emails;
}
});
when(mockEmailManager.findCaseInsensitive(Mockito.anyString())).thenAnswer(new Answer<EmailEntity>() {
@Override
public EmailEntity answer(InvocationOnMock invocation) throws Throwable {
String emailString = invocation.getArgument(0);
String orcidString = emailString.substring(0, (emailString.indexOf("_")));
EmailEntity email = new EmailEntity();
email.setId(emailString);
email.setVisibility(Visibility.PUBLIC);
ProfileEntity entity = new ProfileEntity(orcidString);
entity.setEncryptedPassword("password");
entity.setRecordNameEntity(getRecordName(orcidString));
email.setProfile(entity);
return email;
}
});
}
use of org.mockito.stubbing.Answer in project android_frameworks_base by DirtyUnicorns.
the class IPrintManagerParametersTest method createMockCallbacks.
/**
* Create mock print service callbacks.
*
* @return the callbacks
*/
private PrintServiceCallbacks createMockCallbacks() {
return createMockPrintServiceCallbacks(new Answer<PrinterDiscoverySessionCallbacks>() {
@Override
public PrinterDiscoverySessionCallbacks answer(InvocationOnMock invocation) {
return createMockPrinterDiscoverySessionCallbacks(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) {
// Get the session.
StubbablePrinterDiscoverySession session = ((PrinterDiscoverySessionCallbacks) invocation.getMock()).getSession();
if (session.getPrinters().isEmpty()) {
final String PRINTER_NAME = "good printer";
List<PrinterInfo> printers = new ArrayList<>();
// Add the printer.
mGoodPrinterId = session.getService().generatePrinterId(PRINTER_NAME);
PrinterCapabilitiesInfo capabilities = new PrinterCapabilitiesInfo.Builder(mGoodPrinterId).setMinMargins(new Margins(200, 200, 200, 200)).addMediaSize(MediaSize.ISO_A4, true).addResolution(new Resolution("300x300", "300x300", 300, 300), true).setColorModes(PrintAttributes.COLOR_MODE_COLOR, PrintAttributes.COLOR_MODE_COLOR).build();
PrinterInfo printer = new PrinterInfo.Builder(mGoodPrinterId, PRINTER_NAME, PrinterInfo.STATUS_IDLE).setCapabilities(capabilities).build();
printers.add(printer);
session.addPrinters(printers);
}
onPrinterDiscoverySessionStartCalled();
return null;
}
}, null, null, null, null, null, null);
}
}, null, null);
}
use of org.mockito.stubbing.Answer in project kdeconnect-android by KDE.
the class LanLinkTest method testSendPayload.
public void testSendPayload() throws Exception {
class Downloader extends Thread {
NetworkPackage np;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
public void setNetworkPackage(NetworkPackage networkPackage) {
this.np = networkPackage;
}
public ByteArrayOutputStream getOutputStream() {
return outputStream;
}
@Override
public void run() {
try {
Socket socket = null;
try {
socket = new Socket();
int tcpPort = np.getPayloadTransferInfo().getInt("port");
InetSocketAddress address = new InetSocketAddress(5000);
socket.connect(new InetSocketAddress(address.getAddress(), tcpPort));
np.setPayload(socket.getInputStream(), np.getPayloadSize());
} catch (Exception e) {
try {
socket.close();
} catch (Exception ignored) {
throw ignored;
}
e.printStackTrace();
Log.e("KDE/LanLinkTest", "Exception connecting to remote socket");
throw e;
}
final InputStream input = np.getPayload();
final long fileLength = np.getPayloadSize();
byte[] data = new byte[1024];
long progress = 0, prevProgressPercentage = 0;
int count;
while ((count = input.read(data)) >= 0) {
progress += count;
outputStream.write(data, 0, count);
if (fileLength > 0) {
if (progress >= fileLength)
break;
long progressPercentage = (progress * 100 / fileLength);
if (progressPercentage != prevProgressPercentage) {
prevProgressPercentage = progressPercentage;
}
}
}
outputStream.close();
input.close();
} catch (Exception e) {
Log.e("Downloader Test", "Exception");
e.printStackTrace();
}
}
}
final Downloader downloader = new Downloader();
// Using byte array for payload, try to use input stream as used in real device
String dataString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit." + " Cras vel erat et ante fringilla tristique. Sed consequat ligula at interdum " + "rhoncus. Integer semper enim felis, id sodales tellus aliquet eget." + " Sed fringilla ac metus eget dictum. Aliquam euismod non sem sit" + " amet dapibus. Interdum et malesuada fames ac ante ipsum primis " + "in faucibus. Nam et ligula placerat, varius justo eu, convallis " + "lorem. Nam consequat consequat tortor et gravida. Praesent " + "ultricies tortor eget ex elementum gravida. Suspendisse aliquet " + "erat a orci feugiat dignissim.";
// reallyLongString contains dataString 16 times
String reallyLongString = dataString + dataString;
reallyLongString = reallyLongString + reallyLongString;
reallyLongString = reallyLongString + reallyLongString;
reallyLongString = reallyLongString + reallyLongString;
final byte[] data = reallyLongString.getBytes();
final JSONObject sharePackageJson = new JSONObject("{\"id\":123,\"body\":{\"filename\":\"data.txt\"},\"payloadTransferInfo\":{},\"payloadSize\":8720,\"type\":\"kdeconnect.share\"}");
// Mocking share package
final NetworkPackage sharePackage = Mockito.mock(NetworkPackage.class);
Mockito.when(sharePackage.getType()).thenReturn("kdeconnect.share");
Mockito.when(sharePackage.hasPayload()).thenReturn(true);
Mockito.when(sharePackage.hasPayloadTransferInfo()).thenReturn(true);
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
return sharePackageJson.toString();
}
}).when(sharePackage).serialize();
Mockito.when(sharePackage.getPayload()).thenReturn(new ByteArrayInputStream(data));
Mockito.when(sharePackage.getPayloadSize()).thenReturn((long) data.length);
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
return sharePackageJson.getJSONObject("payloadTransferInfo");
}
}).when(sharePackage).getPayloadTransferInfo();
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
JSONObject object = (JSONObject) invocationOnMock.getArguments()[0];
sharePackageJson.put("payloadTransferInfo", object);
return null;
}
}).when(sharePackage).setPayloadTransferInfo(Mockito.any(JSONObject.class));
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
Log.e("LanLinkTest", "Write to stream");
String stringNetworkPackage = new String((byte[]) invocationOnMock.getArguments()[0]);
final NetworkPackage np = NetworkPackage.unserialize(stringNetworkPackage);
downloader.setNetworkPackage(np);
downloader.start();
return stringNetworkPackage.length();
}
}).when(goodOutputStream).write(Mockito.any(byte[].class));
goodLanLink.sendPackage(sharePackage, callback);
try {
// Wait 1 secs for downloader to finish (if some error, it will continue and assert will fail)
downloader.join(1 * 1000);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
assertEquals(new String(data), new String(downloader.getOutputStream().toByteArray()));
Mockito.verify(callback).onSuccess();
}
use of org.mockito.stubbing.Answer in project opentsdb by OpenTSDB.
the class TestUniqueId method renameRaceCondition.
@Test(expected = IllegalStateException.class)
public void renameRaceCondition() throws Exception {
// Simulate a race between client A(default) and client B.
// A and B rename same UID to different name.
// B waits till A start to invoke PutRequest to start.
uid = new UniqueId(client, table, METRIC, 3);
HBaseClient client_b = mock(HBaseClient.class);
final UniqueId uid_b = new UniqueId(client_b, table, METRIC, 3);
final byte[] foo_id = { 0, 'a', 0x42 };
final byte[] foo_name = { 'f', 'o', 'o' };
ArrayList<KeyValue> kvs = new ArrayList<KeyValue>(1);
kvs.add(new KeyValue(foo_name, ID, METRIC_ARRAY, foo_id));
when(client_b.get(anyGet())).thenReturn(Deferred.fromResult(kvs)).thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(null));
when(client_b.put(anyPut())).thenAnswer(answerTrue());
when(client_b.delete(anyDelete())).thenAnswer(answerTrue());
final Answer<Deferred<Boolean>> the_race = new Answer<Deferred<Boolean>>() {
public Deferred<Boolean> answer(final InvocationOnMock inv) throws Exception {
uid_b.rename("foo", "xyz");
return Deferred.fromResult(true);
}
};
when(client.get(anyGet())).thenReturn(Deferred.fromResult(kvs)).thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(null));
when(client.put(anyPut())).thenAnswer(the_race);
when(client.delete(anyDelete())).thenAnswer(answerTrue());
uid.rename("foo", "bar");
}
Aggregations