Search in sources :

Example 41 with Answer

use of org.mockito.stubbing.Answer in project che by eclipse.

the class GithubImporterPagePresenterTest method onLoadRepoClickedWhenAuthorizeIsFailed.

@Test
public void onLoadRepoClickedWhenAuthorizeIsFailed() throws Exception {
    String userId = "userId";
    CurrentUser user = mock(CurrentUser.class);
    ProfileDto profile = mock(ProfileDto.class);
    when(appContext.getCurrentUser()).thenReturn(user);
    when(user.getProfile()).thenReturn(profile);
    when(profile.getUserId()).thenReturn(userId);
    final Throwable exception = mock(UnauthorizedException.class);
    doAnswer(new Answer() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            presenter.onFailRequest(promiseError);
            return null;
        }
    }).when(presenter).doRequest(any(Promise.class), any(Promise.class), any(Promise.class));
    doReturn(exception).when(promiseError).getCause();
    presenter.onLoadRepoClicked();
    verify(gitHubClientService).getRepositoriesList();
    verify(gitHubClientService).getUserInfo();
    verify(gitHubClientService).getOrganizations();
    verify(gitHubAuthenticator).authenticate(anyString(), asyncCallbackCaptor.capture());
    AsyncCallback<OAuthStatus> asyncCallback = asyncCallbackCaptor.getValue();
    asyncCallback.onFailure(exception);
    verify(view, times(2)).setLoaderVisibility(eq(true));
    verify(view, times(2)).setInputsEnableState(eq(false));
    verify(view, times(2)).setInputsEnableState(eq(true));
    verify(view, never()).setAccountNames((Set<String>) anyObject());
    verify(view, never()).showGithubPanel();
    verify(view, never()).setRepositories(Matchers.<List<ProjectData>>anyObject());
}
Also used : Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) Promise(org.eclipse.che.api.promises.client.Promise) CurrentUser(org.eclipse.che.ide.api.app.CurrentUser) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyString(org.mockito.Matchers.anyString) OAuthStatus(org.eclipse.che.security.oauth.OAuthStatus) ProfileDto(org.eclipse.che.api.user.shared.dto.ProfileDto) ProjectData(org.eclipse.che.plugin.github.ide.load.ProjectData) Test(org.junit.Test)

Example 42 with Answer

use of org.mockito.stubbing.Answer in project hadoop by apache.

the class TestProportionalCapacityPreemptionPolicy method mockLeafQueue.

@SuppressWarnings("rawtypes")
LeafQueue mockLeafQueue(ParentQueue p, Resource tot, int i, Resource[] abs, Resource[] used, Resource[] pending, Resource[] reserved, int[] apps, Resource[] gran) {
    LeafQueue lq = mock(LeafQueue.class);
    ResourceCalculator rc = mCS.getResourceCalculator();
    List<ApplicationAttemptId> appAttemptIdList = new ArrayList<ApplicationAttemptId>();
    when(lq.getTotalPendingResourcesConsideringUserLimit(isA(Resource.class), isA(String.class), eq(false))).thenReturn(pending[i]);
    when(lq.getTotalPendingResourcesConsideringUserLimit(isA(Resource.class), isA(String.class), eq(true))).thenReturn(Resources.componentwiseMax(Resources.subtract(pending[i], reserved[i] == null ? Resources.none() : reserved[i]), Resources.none()));
    // need to set pending resource in resource usage as well
    ResourceUsage ru = new ResourceUsage();
    ru.setPending(pending[i]);
    ru.setUsed(used[i]);
    ru.setReserved(reserved[i]);
    when(lq.getQueueResourceUsage()).thenReturn(ru);
    // consider moving where CapacityScheduler::comparator accessible
    final NavigableSet<FiCaSchedulerApp> qApps = new TreeSet<FiCaSchedulerApp>(new Comparator<FiCaSchedulerApp>() {

        @Override
        public int compare(FiCaSchedulerApp a1, FiCaSchedulerApp a2) {
            return a1.getApplicationAttemptId().compareTo(a2.getApplicationAttemptId());
        }
    });
    // applications are added in global L->R order in queues
    if (apps[i] != 0) {
        Resource aUsed = Resources.divideAndCeil(rc, used[i], apps[i]);
        Resource aPending = Resources.divideAndCeil(rc, pending[i], apps[i]);
        Resource aReserve = Resources.divideAndCeil(rc, reserved[i], apps[i]);
        for (int a = 0; a < apps[i]; ++a) {
            FiCaSchedulerApp mockFiCaApp = mockApp(i, appAlloc, aUsed, aPending, aReserve, gran[i]);
            qApps.add(mockFiCaApp);
            ++appAlloc;
            appAttemptIdList.add(mockFiCaApp.getApplicationAttemptId());
        }
        when(mCS.getAppsInQueue("queue" + (char) ('A' + i - 1))).thenReturn(appAttemptIdList);
    }
    when(lq.getApplications()).thenReturn(qApps);
    @SuppressWarnings("unchecked") OrderingPolicy<FiCaSchedulerApp> so = mock(OrderingPolicy.class);
    when(so.getPreemptionIterator()).thenAnswer(new Answer() {

        public Object answer(InvocationOnMock invocation) {
            return qApps.descendingIterator();
        }
    });
    when(lq.getOrderingPolicy()).thenReturn(so);
    if (setAMResourcePercent != 0.0f) {
        when(lq.getMaxAMResourcePerQueuePercent()).thenReturn(setAMResourcePercent);
    }
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    when(lq.getReadLock()).thenReturn(lock.readLock());
    when(lq.getPriority()).thenReturn(Priority.newInstance(0));
    p.getChildQueues().add(lq);
    return lq;
}
Also used : ResourceUsage(org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceUsage) ArrayList(java.util.ArrayList) Resource(org.apache.hadoop.yarn.api.records.Resource) ApplicationAttemptId(org.apache.hadoop.yarn.api.records.ApplicationAttemptId) Matchers.anyString(org.mockito.Matchers.anyString) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) LeafQueue(org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue) DefaultResourceCalculator(org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator) DominantResourceCalculator(org.apache.hadoop.yarn.util.resource.DominantResourceCalculator) ResourceCalculator(org.apache.hadoop.yarn.util.resource.ResourceCalculator) Answer(org.mockito.stubbing.Answer) TreeSet(java.util.TreeSet) InvocationOnMock(org.mockito.invocation.InvocationOnMock) FiCaSchedulerApp(org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp)

Example 43 with Answer

use of org.mockito.stubbing.Answer in project zeppelin by apache.

the class CorsFilterTest method InvalidCorsFilterTest.

@Test
@SuppressWarnings("rawtypes")
public void InvalidCorsFilterTest() throws IOException, ServletException {
    CorsFilter filter = new CorsFilter();
    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    FilterChain mockedFilterChain = mock(FilterChain.class);
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    when(mockRequest.getHeader("Origin")).thenReturn("http://evillocalhost:8080");
    when(mockRequest.getMethod()).thenReturn("Empty");
    when(mockRequest.getServerName()).thenReturn("evillocalhost");
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            headers[count] = invocationOnMock.getArguments()[1].toString();
            count++;
            return null;
        }
    }).when(mockResponse).addHeader(anyString(), anyString());
    filter.doFilter(mockRequest, mockResponse, mockedFilterChain);
    Assert.assertTrue(headers[0].equals(""));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Example 44 with Answer

use of org.mockito.stubbing.Answer in project zookeeper by apache.

the class LearnerHandlerTest method setUp.

@Before
public void setUp() throws Exception {
    // Intercept when startForwarding is called
    leader = mock(Leader.class);
    when(leader.startForwarding(Matchers.any(LearnerHandler.class), Matchers.anyLong())).thenAnswer(new Answer() {

        public Object answer(InvocationOnMock invocation) {
            currentZxid = (Long) invocation.getArguments()[1];
            return 0;
        }
    });
    sock = mock(Socket.class);
    db = new MockZKDatabase(null);
    learnerHandler = new MockLearnerHandler(sock, leader);
}
Also used : Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Socket(java.net.Socket) Before(org.junit.Before)

Example 45 with Answer

use of org.mockito.stubbing.Answer in project hbase by apache.

the class TestTableInputFormat method createIOEScannerTable.

/**
   * Create a table that IOE's on first scanner next call
   *
   * @throws IOException
   */
static Table createIOEScannerTable(byte[] name, final int failCnt) throws IOException {
    // build up a mock scanner stuff to fail the first time
    Answer<ResultScanner> a = new Answer<ResultScanner>() {

        int cnt = 0;

        @Override
        public ResultScanner answer(InvocationOnMock invocation) throws Throwable {
            // first invocation return the busted mock scanner
            if (cnt++ < failCnt) {
                // create mock ResultScanner that always fails.
                Scan scan = mock(Scan.class);
                // avoid npe
                doReturn("bogus".getBytes()).when(scan).getStartRow();
                ResultScanner scanner = mock(ResultScanner.class);
                // simulate TimeoutException / IOException
                doThrow(new IOException("Injected exception")).when(scanner).next();
                return scanner;
            }
            // otherwise return the real scanner.
            return (ResultScanner) invocation.callRealMethod();
        }
    };
    Table htable = spy(createTable(name));
    doAnswer(a).when(htable).getScanner((Scan) anyObject());
    return htable;
}
Also used : Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ResultScanner(org.apache.hadoop.hbase.client.ResultScanner) Table(org.apache.hadoop.hbase.client.Table) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Scan(org.apache.hadoop.hbase.client.Scan) IOException(java.io.IOException)

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