Search in sources :

Example 81 with Answer

use of org.mockito.stubbing.Answer in project AuthMeReloaded by AuthMe.

the class AbstractResourceClosingTest method initializeSettings.

/** Initialize the settings mock and makes it return the default of any given property by default. */
@SuppressWarnings({ "unchecked", "rawtypes" })
@BeforeClass
public static void initializeSettings() throws IOException, ClassNotFoundException {
    settings = mock(Settings.class);
    given(settings.getProperty(any(Property.class))).willAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) {
            return ((Property<?>) invocation.getArguments()[0]).getDefaultValue();
        }
    });
    TestHelper.setupLogger();
}
Also used : Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Property(ch.jalu.configme.properties.Property) SecuritySettings(fr.xephi.authme.settings.properties.SecuritySettings) Settings(fr.xephi.authme.settings.Settings) BeforeClass(org.junit.BeforeClass)

Example 82 with Answer

use of org.mockito.stubbing.Answer in project AuthMeReloaded by AuthMe.

the class SQLiteIntegrationTest method initializeSettings.

/**
     * Set up the settings mock to return specific values for database settings and load {@link #sqlInitialize}.
     */
@SuppressWarnings({ "unchecked", "rawtypes" })
@BeforeClass
public static void initializeSettings() throws IOException, ClassNotFoundException {
    // Check that we have an implementation for SQLite
    Class.forName("org.sqlite.JDBC");
    settings = mock(Settings.class);
    when(settings.getProperty(any(Property.class))).thenAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return ((Property) invocation.getArguments()[0]).getDefaultValue();
        }
    });
    set(DatabaseSettings.MYSQL_DATABASE, "sqlite-test");
    set(DatabaseSettings.MYSQL_TABLE, "authme");
    TestHelper.setRealLogger();
    Path sqlInitFile = TestHelper.getJarPath(TestHelper.PROJECT_ROOT + "datasource/sql-initialize.sql");
    // Note ljacqu 20160221: It appears that we can only run one statement per Statement.execute() so we split
    // the SQL file by ";\n" as to get the individual statements
    sqlInitialize = new String(Files.readAllBytes(sqlInitFile)).split(";(\\r?)\\n");
}
Also used : Path(java.nio.file.Path) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Property(ch.jalu.configme.properties.Property) Settings(fr.xephi.authme.settings.Settings) DatabaseSettings(fr.xephi.authme.settings.properties.DatabaseSettings) BeforeClass(org.junit.BeforeClass)

Example 83 with Answer

use of org.mockito.stubbing.Answer in project mobile-center-sdk-android by Microsoft.

the class AnalyticsAndroidTest method testAnalyticsListener.

@Test
public void testAnalyticsListener() {
    AnalyticsListener analyticsListener = mock(AnalyticsListener.class);
    Analytics.setListener(analyticsListener);
    Channel channel = mock(Channel.class);
    Analytics.getInstance().onStarted(sContext, "", channel);
    Analytics.trackEvent("event");
    /* First process: enqueue log but network is down... */
    final EventLog log = new EventLog();
    log.setId(randomUUID());
    log.setName("name");
    Analytics.unsetInstance();
    Analytics.setListener(analyticsListener);
    verify(channel).enqueue(any(Log.class), anyString());
    verifyNoMoreInteractions(analyticsListener);
    /* Second process: sending succeeds. */
    final AtomicReference<Channel.GroupListener> groupListener = new AtomicReference<>();
    channel = mock(Channel.class);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Channel.GroupListener listener = (Channel.GroupListener) invocationOnMock.getArguments()[4];
            groupListener.set(listener);
            listener.onBeforeSending(log);
            return null;
        }
    }).when(channel).addGroup(anyString(), anyInt(), anyInt(), anyInt(), any(Channel.GroupListener.class));
    Analytics.unsetInstance();
    Analytics.setListener(analyticsListener);
    Analytics.getInstance().onStarted(sContext, "", channel);
    assertNotNull(groupListener.get());
    groupListener.get().onSuccess(log);
    verify(channel, never()).enqueue(any(Log.class), anyString());
    verify(analyticsListener).onBeforeSending(any(EventLog.class));
    verify(analyticsListener).onSendingSucceeded(any(EventLog.class));
    verifyNoMoreInteractions(analyticsListener);
}
Also used : Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) AnalyticsListener(com.microsoft.azure.mobile.analytics.channel.AnalyticsListener) MobileCenterLog(com.microsoft.azure.mobile.utils.MobileCenterLog) Log(com.microsoft.azure.mobile.ingestion.models.Log) EventLog(com.microsoft.azure.mobile.analytics.ingestion.models.EventLog) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Channel(com.microsoft.azure.mobile.channel.Channel) EventLog(com.microsoft.azure.mobile.analytics.ingestion.models.EventLog) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 84 with Answer

use of org.mockito.stubbing.Answer in project mobile-center-sdk-android by Microsoft.

the class CrashesAndroidTest method testNoDuplicateCallbacksOrSending.

@Test
public void testNoDuplicateCallbacksOrSending() throws InterruptedException {
    /* Crash on 1st process. */
    assertFalse(Crashes.hasCrashedInLastSession());
    android.util.Log.i(TAG, "Process 1");
    Thread.UncaughtExceptionHandler uncaughtExceptionHandler = mock(Thread.UncaughtExceptionHandler.class);
    Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
    Channel channel = mock(Channel.class);
    Crashes.getInstance().onStarted(sContext, "", channel);
    CrashesListener crashesListener = mock(CrashesListener.class);
    when(crashesListener.shouldProcess(any(ErrorReport.class))).thenReturn(true);
    when(crashesListener.shouldAwaitUserConfirmation()).thenReturn(true);
    Crashes.setListener(crashesListener);
    final Error exception = generateStackOverflowError();
    assertTrue(exception.getStackTrace().length > ErrorLogHelper.FRAME_LIMIT);
    final Thread thread = new Thread() {

        @Override
        public void run() {
            throw exception;
        }
    };
    thread.start();
    thread.join();
    assertEquals(ErrorLogHelper.FRAME_LIMIT, exception.getStackTrace().length);
    verify(uncaughtExceptionHandler).uncaughtException(thread, exception);
    assertEquals(2, ErrorLogHelper.getErrorStorageDirectory().listFiles().length);
    verifyZeroInteractions(crashesListener);
    /* Second process: enqueue log but network is down... */
    android.util.Log.i(TAG, "Process 2");
    final AtomicReference<Log> log = new AtomicReference<>();
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            log.set((Log) invocationOnMock.getArguments()[0]);
            return null;
        }
    }).when(channel).enqueue(any(Log.class), anyString());
    Crashes.unsetInstance();
    Crashes.setListener(crashesListener);
    Crashes.getInstance().onStarted(sContext, "", channel);
    waitForCrashesHandlerTasksToComplete();
    /* Check last session error report. */
    assertTrue(Crashes.hasCrashedInLastSession());
    Crashes.getLastSessionCrashReport(new ResultCallback<ErrorReport>() {

        @Override
        public void onResult(ErrorReport errorReport) {
            assertNotNull(errorReport);
            Throwable lastThrowable = errorReport.getThrowable();
            assertTrue(lastThrowable instanceof StackOverflowError);
            assertEquals(ErrorLogHelper.FRAME_LIMIT, lastThrowable.getStackTrace().length);
        }
    });
    /* Waiting user confirmation so no log sent yet. */
    verify(channel, never()).enqueue(any(Log.class), anyString());
    assertEquals(2, ErrorLogHelper.getErrorStorageDirectory().listFiles().length);
    verify(crashesListener).shouldProcess(any(ErrorReport.class));
    verify(crashesListener).shouldAwaitUserConfirmation();
    verifyNoMoreInteractions(crashesListener);
    /* Confirm to resume processing. */
    Crashes.notifyUserConfirmation(Crashes.ALWAYS_SEND);
    verify(channel).enqueue(any(Log.class), anyString());
    assertNotNull(log.get());
    assertEquals(1, ErrorLogHelper.getErrorStorageDirectory().listFiles().length);
    verify(crashesListener).getErrorAttachments(any(ErrorReport.class));
    verifyNoMoreInteractions(crashesListener);
    /* Third process: sending succeeds. */
    android.util.Log.i(TAG, "Process 3");
    final AtomicReference<Channel.GroupListener> groupListener = new AtomicReference<>();
    channel = mock(Channel.class);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Channel.GroupListener listener = (Channel.GroupListener) invocationOnMock.getArguments()[4];
            groupListener.set(listener);
            listener.onBeforeSending(log.get());
            return null;
        }
    }).when(channel).addGroup(anyString(), anyInt(), anyInt(), anyInt(), any(Channel.GroupListener.class));
    Crashes.unsetInstance();
    Crashes.setListener(crashesListener);
    Crashes.getInstance().onStarted(sContext, "", channel);
    waitForCrashesHandlerTasksToComplete();
    assertFalse(Crashes.hasCrashedInLastSession());
    Crashes.getLastSessionCrashReport(new ResultCallback<ErrorReport>() {

        @Override
        public void onResult(ErrorReport errorReport) {
            assertNull(errorReport);
        }
    });
    assertNotNull(groupListener.get());
    groupListener.get().onSuccess(log.get());
    waitForCrashesHandlerTasksToComplete();
    assertEquals(0, ErrorLogHelper.getErrorStorageDirectory().listFiles().length);
    verify(channel, never()).enqueue(any(Log.class), anyString());
    verify(crashesListener).onBeforeSending(any(ErrorReport.class));
    verify(crashesListener).onSendingSucceeded(any(ErrorReport.class));
    verifyNoMoreInteractions(crashesListener);
    /* Verify log was truncated to 256 frames. */
    assertTrue(log.get() instanceof ManagedErrorLog);
    ManagedErrorLog errorLog = (ManagedErrorLog) log.get();
    assertNotNull(errorLog.getException());
    assertNotNull(errorLog.getException().getFrames());
    assertEquals(ErrorLogHelper.FRAME_LIMIT, errorLog.getException().getFrames().size());
}
Also used : MobileCenterLog(com.microsoft.azure.mobile.utils.MobileCenterLog) Log(com.microsoft.azure.mobile.ingestion.models.Log) ManagedErrorLog(com.microsoft.azure.mobile.crashes.ingestion.models.ManagedErrorLog) Channel(com.microsoft.azure.mobile.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ErrorReport(com.microsoft.azure.mobile.crashes.model.ErrorReport) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ManagedErrorLog(com.microsoft.azure.mobile.crashes.ingestion.models.ManagedErrorLog) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.Test)

Example 85 with Answer

use of org.mockito.stubbing.Answer in project mobile-center-sdk-android by Microsoft.

the class UncaughtExceptionHandlerTest method setUp.

@Before
public void setUp() {
    Crashes.unsetInstance();
    mockStatic(MobileCenterLog.class);
    mockStatic(SystemClock.class);
    mockStatic(StorageHelper.PreferencesStorage.class);
    mockStatic(StorageHelper.InternalStorage.class);
    mockStatic(ErrorLogHelper.class);
    mockStatic(DeviceInfoHelper.class);
    mockStatic(System.class);
    when(StorageHelper.PreferencesStorage.getBoolean(KEY_ENABLED, true)).thenReturn(true);
    when(StorageHelper.PreferencesStorage.getBoolean(CRASHES_ENABLED_KEY, true)).thenReturn(true);
    /* Then simulate further changes to state. */
    PowerMockito.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];
            Mockito.when(StorageHelper.PreferencesStorage.getBoolean(CRASHES_ENABLED_KEY, true)).thenReturn(enabled);
            return null;
        }
    }).when(StorageHelper.PreferencesStorage.class);
    StorageHelper.PreferencesStorage.putBoolean(eq(CRASHES_ENABLED_KEY), anyBoolean());
    ManagedErrorLog errorLogMock = mock(ManagedErrorLog.class);
    when(ErrorLogHelper.getErrorStorageDirectory()).thenReturn(new File("."));
    when(ErrorLogHelper.createErrorLog(any(Context.class), any(Thread.class), any(Throwable.class), Matchers.<Map<Thread, StackTraceElement[]>>any(), anyLong(), anyBoolean())).thenReturn(errorLogMock);
    when(errorLogMock.getId()).thenReturn(UUID.randomUUID());
    mDefaultExceptionHandler = mock(Thread.UncaughtExceptionHandler.class);
    Thread.setDefaultUncaughtExceptionHandler(mDefaultExceptionHandler);
    mExceptionHandler = new UncaughtExceptionHandler();
    MobileCenter.configure(mock(Application.class), "dummy");
}
Also used : Context(android.content.Context) Answer(org.mockito.stubbing.Answer) ManagedErrorLog(com.microsoft.azure.mobile.crashes.ingestion.models.ManagedErrorLog) InvocationOnMock(org.mockito.invocation.InvocationOnMock) StorageHelper(com.microsoft.azure.mobile.utils.storage.StorageHelper) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) File(java.io.File) Application(android.app.Application) Before(org.junit.Before)

Aggregations

Answer (org.mockito.stubbing.Answer)308 InvocationOnMock (org.mockito.invocation.InvocationOnMock)289 Test (org.junit.Test)180 Mockito.doAnswer (org.mockito.Mockito.doAnswer)114 Before (org.junit.Before)47 Matchers.anyString (org.mockito.Matchers.anyString)42 HashMap (java.util.HashMap)36 ArrayList (java.util.ArrayList)35 PowerMockito.doAnswer (org.powermock.api.mockito.PowerMockito.doAnswer)29 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)26 AtomicReference (java.util.concurrent.atomic.AtomicReference)24 IOException (java.io.IOException)23 Context (android.content.Context)20 File (java.io.File)19 HashSet (java.util.HashSet)17 List (java.util.List)16 Map (java.util.Map)13 Test (org.testng.annotations.Test)13 CountDownLatch (java.util.concurrent.CountDownLatch)12 Handler (android.os.Handler)11