Search in sources :

Example 36 with Answer

use of org.mockito.stubbing.Answer in project byte-buddy by raphw.

the class AgentBuilderDefaultTest method testExecutingTransformerDoesNotRecurseWithModules.

@Test
@JavaVersionRule.Enforce(9)
public void testExecutingTransformerDoesNotRecurseWithModules() throws Exception {
    final AgentBuilder.Default.ExecutingTransformer executingTransformer = new AgentBuilder.Default.ExecutingTransformer(byteBuddy, listener, poolStrategy, typeStrategy, locationStrategy, mock(AgentBuilder.Default.NativeMethodStrategy.class), initializationStrategy, mock(AgentBuilder.Default.BootstrapInjectionStrategy.class), AgentBuilder.LambdaInstrumentationStrategy.DISABLED, AgentBuilder.DescriptionStrategy.Default.HYBRID, mock(AgentBuilder.FallbackStrategy.class), mock(AgentBuilder.InstallationListener.class), mock(AgentBuilder.RawMatcher.class), mock(AgentBuilder.Default.Transformation.class), new AgentBuilder.CircularityLock.Default());
    final ClassLoader classLoader = mock(ClassLoader.class);
    final ProtectionDomain protectionDomain = mock(ProtectionDomain.class);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertThat(executingTransformer.transform(JavaModule.ofType(Object.class).unwrap(), classLoader, FOO, Object.class, protectionDomain, new byte[0]), nullValue(byte[].class));
            return null;
        }
    }).when(listener).onComplete(FOO, classLoader, JavaModule.ofType(Object.class), true);
    assertThat(executingTransformer.transform(JavaModule.of(Object.class).unwrap(), classLoader, FOO, Object.class, protectionDomain, new byte[0]), nullValue(byte[].class));
    verify(listener).onComplete(FOO, classLoader, JavaModule.ofType(Object.class), true);
}
Also used : ProtectionDomain(java.security.ProtectionDomain) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.Test)

Example 37 with Answer

use of org.mockito.stubbing.Answer in project elasticsearch by elastic.

the class RemoteScrollableHitSourceTests method testTooLargeResponse.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void testTooLargeResponse() throws Exception {
    ContentTooLongException tooLong = new ContentTooLongException("too long!");
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).then(new Answer<Future<HttpResponse>>() {

        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            HeapBufferedAsyncResponseConsumer consumer = (HeapBufferedAsyncResponseConsumer) invocationOnMock.getArguments()[1];
            FutureCallback callback = (FutureCallback) invocationOnMock.getArguments()[3];
            assertEquals(new ByteSizeValue(100, ByteSizeUnit.MB).bytesAsInt(), consumer.getBufferLimit());
            callback.failed(tooLong);
            return null;
        }
    });
    RemoteScrollableHitSource source = sourceWithMockedClient(true, httpClient);
    AtomicBoolean called = new AtomicBoolean();
    Consumer<Response> checkResponse = r -> called.set(true);
    Throwable e = expectThrows(RuntimeException.class, () -> source.doStartNextScroll(FAKE_SCROLL_ID, timeValueMillis(0), checkResponse));
    // Unwrap the some artifacts from the test
    while (e.getMessage().equals("failed")) {
        e = e.getCause();
    }
    // This next exception is what the user sees
    assertEquals("Remote responded with a chunk that was too large. Use a smaller batch size.", e.getMessage());
    // And that exception is reported as being caused by the underlying exception returned by the client
    assertSame(tooLong, e.getCause());
    assertFalse(called.get());
}
Also used : Response(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource.Response) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) ScheduledFuture(java.util.concurrent.ScheduledFuture) URL(java.net.URL) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) StatusLine(org.apache.http.StatusLine) HeapBufferedAsyncResponseConsumer(org.elasticsearch.client.HeapBufferedAsyncResponseConsumer) Future(java.util.concurrent.Future) After(org.junit.After) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) Streams(org.elasticsearch.common.io.Streams) ThreadPool(org.elasticsearch.threadpool.ThreadPool) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) Matchers.any(org.mockito.Matchers.any) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) Version(org.elasticsearch.Version) RestStatus(org.elasticsearch.rest.RestStatus) TimeValue.timeValueMinutes(org.elasticsearch.common.unit.TimeValue.timeValueMinutes) Matchers.containsString(org.hamcrest.Matchers.containsString) Mockito.mock(org.mockito.Mockito.mock) RestClient(org.elasticsearch.client.RestClient) ContentTooLongException(org.apache.http.ContentTooLongException) ParsingException(org.elasticsearch.common.ParsingException) BasicStatusLine(org.apache.http.message.BasicStatusLine) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SearchRequest(org.elasticsearch.action.search.SearchRequest) BackoffPolicy(org.elasticsearch.action.bulk.BackoffPolicy) BytesArray(org.elasticsearch.common.bytes.BytesArray) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) Answer(org.mockito.stubbing.Answer) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TimeValue(org.elasticsearch.common.unit.TimeValue) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) TimeValue.timeValueMillis(org.elasticsearch.common.unit.TimeValue.timeValueMillis) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ESTestCase(org.elasticsearch.test.ESTestCase) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) FileSystemUtils(org.elasticsearch.common.io.FileSystemUtils) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) Matchers.empty(org.hamcrest.Matchers.empty) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) FutureCallback(org.apache.http.concurrent.FutureCallback) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) InputStreamReader(java.io.InputStreamReader) Consumer(java.util.function.Consumer) ProtocolVersion(org.apache.http.ProtocolVersion) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) HttpResponse(org.apache.http.HttpResponse) InputStreamEntity(org.apache.http.entity.InputStreamEntity) HttpHost(org.apache.http.HttpHost) ContentTooLongException(org.apache.http.ContentTooLongException) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HeapBufferedAsyncResponseConsumer(org.elasticsearch.client.HeapBufferedAsyncResponseConsumer) Response(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource.Response) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) FutureCallback(org.apache.http.concurrent.FutureCallback)

Example 38 with Answer

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

the class GithubImporterPagePresenterTest method onLoadRepoClickedWhenGetUserReposIsSuccessful.

@Test
public void onLoadRepoClickedWhenGetUserReposIsSuccessful() throws Exception {
    doAnswer(new Answer() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            presenter.onSuccessRequest(jsArrayMixed);
            return null;
        }
    }).when(presenter).doRequest(any(Promise.class), any(Promise.class), any(Promise.class));
    when(view.getAccountName()).thenReturn("AccountName");
    presenter.onLoadRepoClicked();
    verify(gitHubClientService).getRepositoriesList();
    verify(gitHubClientService).getUserInfo();
    verify(gitHubClientService).getOrganizations();
    verify(view).setLoaderVisibility(eq(true));
    verify(view).setInputsEnableState(eq(false));
    verify(view).setLoaderVisibility(eq(false));
    verify(view).setInputsEnableState(eq(true));
    verify(view).setAccountNames(Matchers.<Set>anyObject());
    verify(view, times(2)).showGithubPanel();
    verify(view).setRepositories(Matchers.<List<ProjectData>>anyObject());
    verify(view).reset();
}
Also used : Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) Promise(org.eclipse.che.api.promises.client.Promise) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ProjectData(org.eclipse.che.plugin.github.ide.load.ProjectData) Test(org.junit.Test)

Example 39 with Answer

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

the class GithubImporterPagePresenterTest method onLoadRepoClickedWhenGetUserReposIsFailed.

@Test
public void onLoadRepoClickedWhenGetUserReposIsFailed() throws Exception {
    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));
    presenter.onLoadRepoClicked();
    verify(gitHubClientService).getRepositoriesList();
    verify(gitHubClientService).getUserInfo();
    verify(gitHubClientService).getOrganizations();
    verify(view).setLoaderVisibility(eq(true));
    verify(view).setInputsEnableState(eq(false));
    verify(view).setLoaderVisibility(eq(false));
    verify(view).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) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyString(org.mockito.Matchers.anyString) ProjectData(org.eclipse.che.plugin.github.ide.load.ProjectData) Test(org.junit.Test)

Example 40 with Answer

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

the class GithubImporterPagePresenterTest method onLoadRepoClickedWhenAuthorizeIsSuccessful.

@Test
public void onLoadRepoClickedWhenAuthorizeIsSuccessful() throws Exception {
    doAnswer(new Answer() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            presenter.onFailRequest(promiseError);
            return null;
        }
    }).doAnswer(new Answer() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            presenter.onSuccessRequest(jsArrayMixed);
            return null;
        }
    }).when(presenter).doRequest(any(Promise.class), any(Promise.class), any(Promise.class));
    final Throwable exception = mock(UnauthorizedException.class);
    String userId = "userId";
    CurrentUser user = mock(CurrentUser.class);
    ProfileDto profile = mock(ProfileDto.class);
    doReturn(exception).when(promiseError).getCause();
    when(appContext.getCurrentUser()).thenReturn(user);
    when(user.getProfile()).thenReturn(profile);
    when(profile.getUserId()).thenReturn(userId);
    presenter.onLoadRepoClicked();
    verify(gitHubClientService).getRepositoriesList();
    verify(gitHubClientService).getUserInfo();
    verify(gitHubClientService).getOrganizations();
    verify(gitHubAuthenticator).authenticate(anyString(), asyncCallbackCaptor.capture());
    AsyncCallback<OAuthStatus> asyncCallback = asyncCallbackCaptor.getValue();
    asyncCallback.onSuccess(null);
    verify(view, times(3)).setLoaderVisibility(eq(true));
    verify(view, times(3)).setInputsEnableState(eq(false));
    verify(view, times(3)).setInputsEnableState(eq(true));
}
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) Test(org.junit.Test)

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