Search in sources :

Example 61 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project AuthMeReloaded by AuthMe.

the class HasPermissionCheckerTest method shouldShowUsageInfo.

@Test
public void shouldShowUsageInfo() {
    // given
    CommandSender sender = mock(CommandSender.class);
    // when
    hasPermissionChecker.execute(sender, emptyList());
    // then
    ArgumentCaptor<String> msgCaptor = ArgumentCaptor.forClass(String.class);
    verify(sender, atLeast(2)).sendMessage(msgCaptor.capture());
    assertThat(msgCaptor.getAllValues().stream().anyMatch(msg -> msg.contains("/authme debug perm bobby my.perm.node")), equalTo(true));
}
Also used : PermissionNode(fr.xephi.authme.permission.PermissionNode) ClassCollector(fr.xephi.authme.ClassCollector) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) AdminPermission(fr.xephi.authme.permission.AdminPermission) Player(org.bukkit.entity.Player) Assert.assertThat(org.junit.Assert.assertThat) PermissionsManager(fr.xephi.authme.permission.PermissionsManager) ArgumentCaptor(org.mockito.ArgumentCaptor) BDDMockito.given(org.mockito.BDDMockito.given) Arrays.asList(java.util.Arrays.asList) MockitoHamcrest.argThat(org.mockito.hamcrest.MockitoHamcrest.argThat) Mockito.atLeast(org.mockito.Mockito.atLeast) TestHelper(fr.xephi.authme.TestHelper) InjectMocks(org.mockito.InjectMocks) CommandSender(org.bukkit.command.CommandSender) Collections.emptyList(java.util.Collections.emptyList) BukkitService(fr.xephi.authme.service.BukkitService) Test(org.junit.Test) Collectors(java.util.stream.Collectors) Mockito.verify(org.mockito.Mockito.verify) List(java.util.List) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Matchers.containsString(org.hamcrest.Matchers.containsString) Mockito.mock(org.mockito.Mockito.mock) CommandSender(org.bukkit.command.CommandSender) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.Test)

Example 62 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project beam by apache.

the class FirestoreV1FnRunQueryTest method resumeFromLastReadValue.

@Override
public void resumeFromLastReadValue() throws Exception {
    TestData testData = TestData.fieldEqualsBar().setProjectId(projectId).setOrderFunction(f -> Collections.singletonList(Order.newBuilder().setDirection(Direction.ASCENDING).setField(f).build())).build();
    RunQueryRequest request2 = RunQueryRequest.newBuilder().setParent(String.format("projects/%s/databases/(default)/document", projectId)).setStructuredQuery(testData.request.getStructuredQuery().toBuilder().setStartAt(Cursor.newBuilder().setBefore(false).addValues(Value.newBuilder().setStringValue("bar")))).build();
    List<RunQueryResponse> responses = ImmutableList.of(testData.response1, testData.response2, testData.response3);
    when(responseStream1.iterator()).thenReturn(new AbstractIterator<RunQueryResponse>() {

        private int invocationCount = 1;

        @Override
        protected RunQueryResponse computeNext() {
            int count = invocationCount++;
            if (count == 1) {
                return responses.get(0);
            } else if (count == 2) {
                return responses.get(1);
            } else {
                throw RETRYABLE_ERROR;
            }
        }
    });
    when(callable.call(testData.request)).thenReturn(responseStream1);
    doNothing().when(attempt).checkCanRetry(any(), eq(RETRYABLE_ERROR));
    when(responseStream2.iterator()).thenReturn(ImmutableList.of(responses.get(2)).iterator());
    when(callable.call(request2)).thenReturn(responseStream2);
    when(stub.runQueryCallable()).thenReturn(callable);
    when(ff.getFirestoreStub(any())).thenReturn(stub);
    when(ff.getRpcQos(any())).thenReturn(rpcQos);
    when(rpcQos.newReadAttempt(any())).thenReturn(attempt);
    when(attempt.awaitSafeToProceed(any())).thenReturn(true);
    ArgumentCaptor<RunQueryResponse> responsesCaptor = ArgumentCaptor.forClass(RunQueryResponse.class);
    doNothing().when(processContext).output(responsesCaptor.capture());
    when(processContext.element()).thenReturn(testData.request);
    RunQueryFn fn = new RunQueryFn(clock, ff, rpcQosOptions);
    runFunction(fn);
    List<RunQueryResponse> allValues = responsesCaptor.getAllValues();
    assertEquals(responses, allValues);
    verify(callable, times(1)).call(testData.request);
    verify(callable, times(1)).call(request2);
    verify(attempt, times(3)).recordStreamValue(any());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) RunQueryRequest(com.google.firestore.v1.RunQueryRequest) FieldReference(com.google.firestore.v1.StructuredQuery.FieldReference) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Mock(org.mockito.Mock) Direction(com.google.firestore.v1.StructuredQuery.Direction) FirestoreStub(com.google.cloud.firestore.v1.stub.FirestoreStub) Operator(com.google.firestore.v1.StructuredQuery.FieldFilter.Operator) ImmutableMap(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap) Function(java.util.function.Function) AbstractIterator(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.AbstractIterator) ArgumentCaptor(org.mockito.ArgumentCaptor) Value(com.google.firestore.v1.Value) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Objects.requireNonNull(java.util.Objects.requireNonNull) ServerStream(com.google.api.gax.rpc.ServerStream) ServerStreamingCallable(com.google.api.gax.rpc.ServerStreamingCallable) StructuredQuery(com.google.firestore.v1.StructuredQuery) Filter(com.google.firestore.v1.StructuredQuery.Filter) Document(com.google.firestore.v1.Document) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) Mockito.doNothing(org.mockito.Mockito.doNothing) Mockito.when(org.mockito.Mockito.when) FieldFilter(com.google.firestore.v1.StructuredQuery.FieldFilter) Mockito.verify(org.mockito.Mockito.verify) RunQueryFn(org.apache.beam.sdk.io.gcp.firestore.FirestoreV1ReadFn.RunQueryFn) List(java.util.List) Cursor(com.google.firestore.v1.Cursor) ImmutableList(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList) RunQueryResponse(com.google.firestore.v1.RunQueryResponse) Order(com.google.firestore.v1.StructuredQuery.Order) CollectionSelector(com.google.firestore.v1.StructuredQuery.CollectionSelector) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) RunQueryResponse(com.google.firestore.v1.RunQueryResponse) RunQueryRequest(com.google.firestore.v1.RunQueryRequest) RunQueryFn(org.apache.beam.sdk.io.gcp.firestore.FirestoreV1ReadFn.RunQueryFn)

Example 63 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project hazelcast by hazelcast.

the class ElasticSourcePTest method when_runProcessorWithOptionsFn_then_shouldUseOptionsFnForScrollRequest.

@Test
public void when_runProcessorWithOptionsFn_then_shouldUseOptionsFnForScrollRequest() throws Exception {
    SearchHit hit = new SearchHit(0, "id-0", new Text("ignored"), emptyMap(), emptyMap());
    hit.sourceRef(new BytesArray(HIT_SOURCE));
    when(response.getHits()).thenReturn(new SearchHits(new SearchHit[] { hit }, new TotalHits(1, EQUAL_TO), Float.NaN));
    SearchResponse response2 = mock(SearchResponse.class);
    when(response2.getHits()).thenReturn(new SearchHits(new SearchHit[] {}, new TotalHits(1, EQUAL_TO), Float.NaN));
    when(mockClient.scroll(any(), any())).thenReturn(response2);
    // get different instance than default
    TestSupport testSupport = runProcessor(request -> {
        Builder builder = RequestOptions.DEFAULT.toBuilder();
        builder.addHeader("TestHeader", "value");
        return builder.build();
    });
    testSupport.expectOutput(newArrayList(HIT_SOURCE));
    ArgumentCaptor<RequestOptions> captor = forClass(RequestOptions.class);
    verify(mockClient).scroll(any(), captor.capture());
    RequestOptions capturedOptions = captor.getValue();
    assertThat(capturedOptions.getHeaders()).extracting(h -> tuple(h.getName(), h.getValue())).containsExactly(tuple("TestHeader", "value"));
}
Also used : TotalHits(org.apache.lucene.search.TotalHits) RestClient(org.elasticsearch.client.RestClient) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) SearchHits(org.elasticsearch.search.SearchHits) QuickTest(com.hazelcast.test.annotation.QuickTest) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RunWith(org.junit.runner.RunWith) TestOutbox(com.hazelcast.jet.core.test.TestOutbox) SearchRequest(org.elasticsearch.action.search.SearchRequest) Node(org.elasticsearch.client.Node) Builder(org.elasticsearch.client.RequestOptions.Builder) Prirep(com.hazelcast.jet.elastic.impl.Shard.Prirep) BytesArray(org.elasticsearch.common.bytes.BytesArray) ArgumentCaptor(org.mockito.ArgumentCaptor) Text(org.elasticsearch.common.text.Text) SearchResponse(org.elasticsearch.action.search.SearchResponse) RequestOptions(org.elasticsearch.client.RequestOptions) RETURNS_DEEP_STUBS(org.mockito.Mockito.RETURNS_DEEP_STUBS) Before(org.junit.Before) SearchHit(org.elasticsearch.search.SearchHit) FunctionEx(com.hazelcast.function.FunctionEx) Collections.emptyMap(java.util.Collections.emptyMap) ActionRequest(org.elasticsearch.action.ActionRequest) SliceBuilder(org.elasticsearch.search.slice.SliceBuilder) Assertions.tuple(org.assertj.core.api.Assertions.tuple) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) Category(org.junit.experimental.categories.Category) EQUAL_TO(org.apache.lucene.search.TotalHits.Relation.EQUAL_TO) Serializable(java.io.Serializable) Mockito.verify(org.mockito.Mockito.verify) TotalHits(org.apache.lucene.search.TotalHits) List(java.util.List) ArgumentCaptor.forClass(org.mockito.ArgumentCaptor.forClass) TestSupport(com.hazelcast.jet.core.test.TestSupport) HazelcastParallelClassRunner(com.hazelcast.test.HazelcastParallelClassRunner) SearchScrollRequest(org.elasticsearch.action.search.SearchScrollRequest) Lists.newArrayList(org.assertj.core.util.Lists.newArrayList) Mockito.mock(org.mockito.Mockito.mock) BytesArray(org.elasticsearch.common.bytes.BytesArray) SearchHit(org.elasticsearch.search.SearchHit) RequestOptions(org.elasticsearch.client.RequestOptions) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) Builder(org.elasticsearch.client.RequestOptions.Builder) SliceBuilder(org.elasticsearch.search.slice.SliceBuilder) TestSupport(com.hazelcast.jet.core.test.TestSupport) Text(org.elasticsearch.common.text.Text) SearchHits(org.elasticsearch.search.SearchHits) SearchResponse(org.elasticsearch.action.search.SearchResponse) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Example 64 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project powermock by powermock.

the class AnnotationEnabler method processAnnotationOn.

private Object processAnnotationOn(Captor annotation, Field field) {
    Class<?> type = field.getType();
    if (!ArgumentCaptor.class.isAssignableFrom(type)) {
        throw new MockitoException("@Captor field must be of the type ArgumentCaptor.\n" + "Field: '" + field.getName() + "' has wrong type\n" + "For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class.");
    }
    Class cls = new GenericMaster().getGenericType(field);
    return ArgumentCaptor.forClass(cls);
}
Also used : GenericMaster(org.mockito.internal.util.reflection.GenericMaster) ArgumentCaptor(org.mockito.ArgumentCaptor) MockitoException(org.mockito.exceptions.base.MockitoException)

Example 65 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project stashbot by palantir.

the class MockGitCommandBuilderFactory method reset.

@SuppressWarnings("unchecked")
private void reset() {
    // list of changesets in order
    changesets = new ArrayList<String>();
    blacklistedChangesets = new HashSet<String>();
    // for each hash, list of branches that contain said hash
    branchMap = new HashMap<String, List<String>>();
    gcbf = Mockito.mock(GitCommandBuilderFactory.class);
    grlb = Mockito.mock(GitRevListBuilder.class);
    gscb = Mockito.mock(GitScmCommandBuilder.class);
    branchCommandBuilder = Mockito.mock(GitScmCommandBuilder.class);
    cmd = Mockito.mock(GitCommand.class);
    branchCommand = Mockito.mock(GitCommand.class);
    // RevList cmd
    Mockito.when(gcbf.builder()).thenReturn(gscb);
    Mockito.when(gcbf.builder(Mockito.any(Repository.class))).thenReturn(gscb);
    Mockito.when(gscb.revList()).thenReturn(grlb);
    final ArgumentCaptor<CommandOutputHandler<Object>> cohCaptor = (ArgumentCaptor<CommandOutputHandler<Object>>) (Object) ArgumentCaptor.forClass(CommandOutputHandler.class);
    Mockito.when(grlb.build(cohCaptor.capture())).thenReturn(cmd);
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            CommandOutputHandler<Object> coh = cohCaptor.getValue();
            List<String> finalCS = new ArrayList<String>();
            for (String cs : changesets) {
                if (!blacklistedChangesets.contains(cs)) {
                    finalCS.add(cs);
                }
            }
            String str = StringUtils.join(finalCS, "\n") + "\n";
            InputStream is = new ByteArrayInputStream(str.getBytes());
            coh.process(is);
            return null;
        }
    }).when(cmd).call();
    // Branch cmd - returns list of all branches
    final ArgumentCaptor<CommandOutputHandler<Object>> branchCOHCaptor = (ArgumentCaptor<CommandOutputHandler<Object>>) (Object) ArgumentCaptor.forClass(CommandOutputHandler.class);
    Mockito.when(gscb.command("branch")).thenReturn(branchCommandBuilder);
    Mockito.when(branchCommandBuilder.build(branchCOHCaptor.capture())).thenReturn(branchCommand);
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            CommandOutputHandler<Object> coh = branchCOHCaptor.getValue();
            String output = "";
            List<String> branches = new ArrayList<String>(branchMap.keySet());
            for (String branch : branches) {
                output = output + "  " + branch + "\n";
            }
            InputStream is = new ByteArrayInputStream(output.getBytes());
            coh.process(is);
            return null;
        }
    }).when(branchCommand).call();
}
Also used : ArgumentCaptor(org.mockito.ArgumentCaptor) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) GitScmCommandBuilder(com.atlassian.stash.scm.git.GitScmCommandBuilder) GitRevListBuilder(com.atlassian.stash.scm.git.revlist.GitRevListBuilder) CommandOutputHandler(com.atlassian.stash.scm.CommandOutputHandler) GitCommand(com.atlassian.stash.scm.git.GitCommand) Repository(com.atlassian.stash.repository.Repository) ByteArrayInputStream(java.io.ByteArrayInputStream) GitCommandBuilderFactory(com.atlassian.stash.scm.git.GitCommandBuilderFactory) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

ArgumentCaptor (org.mockito.ArgumentCaptor)231 Mockito.verify (org.mockito.Mockito.verify)156 List (java.util.List)128 Test (org.junit.Test)116 Mockito.mock (org.mockito.Mockito.mock)113 Mockito.when (org.mockito.Mockito.when)100 Test (org.junit.jupiter.api.Test)86 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)85 Mockito (org.mockito.Mockito)85 Map (java.util.Map)76 BeforeEach (org.junit.jupiter.api.BeforeEach)72 Arrays (java.util.Arrays)69 Collectors (java.util.stream.Collectors)69 Collections (java.util.Collections)68 Before (org.junit.Before)65 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)64 Mockito.times (org.mockito.Mockito.times)64 ArrayList (java.util.ArrayList)60 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)60 Mockito.never (org.mockito.Mockito.never)58