Search in sources :

Example 11 with ArgumentCaptor

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

the class CcTrayConfigChangeHandlerTest method shouldUpdateCacheWithAppropriateViewersForProjectStatusWhenPipelineConfigChanges.

@Test
public void shouldUpdateCacheWithAppropriateViewersForProjectStatusWhenPipelineConfigChanges() {
    String pipeline1Stage = "pipeline1 :: stage1";
    String pipeline1job = "pipeline1 :: stage1 :: job1";
    ProjectStatus statusOfPipeline1StageInCache = new ProjectStatus(pipeline1Stage, "OldActivity", "OldStatus", "OldLabel", new Date(), "p1-stage-url");
    ProjectStatus statusOfPipeline1JobInCache = new ProjectStatus(pipeline1job, "OldActivity-Job", "OldStatus-Job", "OldLabel-Job", new Date(), "p1-job-url");
    when(cache.get(pipeline1Stage)).thenReturn(statusOfPipeline1StageInCache);
    when(cache.get(pipeline1job)).thenReturn(statusOfPipeline1JobInCache);
    when(ccTrayViewAuthority.groupsAndTheirViewers()).thenReturn(m("group1", viewers("user1", "user2"), "group2", viewers("user3")));
    PipelineConfig pipeline1Config = GoConfigMother.pipelineHavingJob("pipeline1", "stage1", "job1", "arts", "dir").pipelineConfigByName(new CaseInsensitiveString("pipeline1"));
    handler.call(pipeline1Config, "group1");
    ArgumentCaptor<ArrayList<ProjectStatus>> argumentCaptor = new ArgumentCaptor<>();
    verify(cache).putAll(argumentCaptor.capture());
    List<ProjectStatus> allValues = argumentCaptor.getValue();
    assertThat(allValues.get(0).name(), is(pipeline1Stage));
    assertThat(allValues.get(0).viewers().contains("user1"), is(true));
    assertThat(allValues.get(0).viewers().contains("user2"), is(true));
    assertThat(allValues.get(0).viewers().contains("user3"), is(false));
    assertThat(allValues.get(1).name(), is(pipeline1job));
    assertThat(allValues.get(1).viewers().contains("user1"), is(true));
    assertThat(allValues.get(1).viewers().contains("user2"), is(true));
    assertThat(allValues.get(1).viewers().contains("user3"), is(false));
}
Also used : ProjectStatus(com.thoughtworks.go.domain.activity.ProjectStatus) ArgumentCaptor(org.mockito.ArgumentCaptor) ArrayList(java.util.ArrayList) Date(java.util.Date) Test(org.junit.Test)

Example 12 with ArgumentCaptor

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

the class PluggableTaskBuilderTest method shouldPublishErrorMessageIfPluginThrowsAnException.

@Test
public void shouldPublishErrorMessageIfPluginThrowsAnException() throws CruiseControlException {
    PluggableTask task = mock(PluggableTask.class);
    when(task.getPluginConfiguration()).thenReturn(new PluginConfiguration());
    PluggableTaskBuilder taskBuilder = new PluggableTaskBuilder(runIfConfigs, cancelBuilder, pluggableTask, TEST_PLUGIN_ID, "test-directory") {

        @Override
        protected ExecutionResult executeTask(Task task, BuildLogElement buildLogElement, DefaultGoPublisher publisher, EnvironmentVariableContext environmentVariableContext) {
            throw new RuntimeException("err");
        }
    };
    when(pluginManager.doOn(eq(Task.class), eq(TEST_PLUGIN_ID), any(ActionWithReturn.class))).thenAnswer(new Answer<ExecutionResult>() {

        @Override
        public ExecutionResult answer(InvocationOnMock invocationOnMock) throws Throwable {
            ActionWithReturn<Task, ExecutionResult> actionWithReturn = (ActionWithReturn<Task, ExecutionResult>) invocationOnMock.getArguments()[2];
            return actionWithReturn.execute(mock(Task.class), pluginDescriptor);
        }
    });
    try {
        taskBuilder.build(buildLogElement, goPublisher, variableContext, taskExtension);
        fail("expected exception to be thrown");
    } catch (Exception e) {
        ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
        verify(goPublisher).consumeLine(captor.capture());
        String error = "Error: err";
        assertThat(captor.getValue(), is(error));
        assertThat(e.getMessage(), is(new RuntimeException("err").toString()));
    }
}
Also used : PluggableTask(com.thoughtworks.go.config.pluggabletask.PluggableTask) ArgumentCaptor(org.mockito.ArgumentCaptor) BuildLogElement(com.thoughtworks.go.domain.BuildLogElement) ExecutionResult(com.thoughtworks.go.plugin.api.response.execution.ExecutionResult) PluggableTask(com.thoughtworks.go.config.pluggabletask.PluggableTask) CruiseControlException(com.thoughtworks.go.util.command.CruiseControlException) DefaultGoPublisher(com.thoughtworks.go.work.DefaultGoPublisher) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PluginConfiguration(com.thoughtworks.go.domain.config.PluginConfiguration) ActionWithReturn(com.thoughtworks.go.plugin.infra.ActionWithReturn) EnvironmentVariableContext(com.thoughtworks.go.util.command.EnvironmentVariableContext) Test(org.junit.Test)

Example 13 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 14 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project OpenAM by OpenRock.

the class PolicyResourceDelegateTest method shouldHandleFailureToDeleteFailedCreationOfPolicies.

@Test(expectedExceptions = ResourceException.class)
public void shouldHandleFailureToDeleteFailedCreationOfPolicies() throws ResourceException {
    //Given
    //Given
    Context context = mock(Context.class);
    Set<JsonValue> policies = new HashSet<JsonValue>();
    JsonValue policyOne = json(object(field("name", "POLICY_ONE")));
    JsonValue policyTwo = json(object(field("name", "POLICY_TWO")));
    policies.add(policyOne);
    policies.add(policyTwo);
    ResourceResponse createdPolicyOne = newResourceResponse("ID_1", "REVISION_1", json(object()));
    ResourceException createException = mock(ResourceException.class);
    ResourceException deleteException = mock(ResourceException.class);
    Promise<ResourceResponse, ResourceException> createPolicyOnePromise = Promises.newResultPromise(createdPolicyOne);
    Promise<ResourceResponse, ResourceException> createPolicyTwoPromise = Promises.newExceptionPromise(createException);
    Promise<ResourceResponse, ResourceException> deletePolicyOnePromise = Promises.newExceptionPromise(deleteException);
    given(policyResource.handleCreate(eq(context), Matchers.<CreateRequest>anyObject())).willReturn(createPolicyOnePromise).willReturn(createPolicyTwoPromise);
    given(policyResource.handleDelete(eq(context), Matchers.<DeleteRequest>anyObject())).willReturn(deletePolicyOnePromise);
    //When
    try {
        delegate.createPolicies(context, policies).getOrThrowUninterruptibly();
    } catch (ResourceException e) {
        //Then
        ArgumentCaptor<DeleteRequest> requestCaptor = ArgumentCaptor.forClass(DeleteRequest.class);
        verify(policyResource).handleDelete(eq(context), requestCaptor.capture());
        assertThat(requestCaptor.getValue().getResourcePathObject().leaf()).isEqualTo("ID_1");
        assertThat(e).isEqualTo(deleteException);
        throw e;
    }
}
Also used : Context(org.forgerock.services.context.Context) ArgumentCaptor(org.mockito.ArgumentCaptor) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) CreateRequest(org.forgerock.json.resource.CreateRequest) JsonValue(org.forgerock.json.JsonValue) ResourceException(org.forgerock.json.resource.ResourceException) DeleteRequest(org.forgerock.json.resource.DeleteRequest) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 15 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)

Aggregations

ArgumentCaptor (org.mockito.ArgumentCaptor)33 List (java.util.List)16 Matchers.anyString (org.mockito.Matchers.anyString)15 Test (org.testng.annotations.Test)15 ArrayList (java.util.ArrayList)14 HashMap (java.util.HashMap)13 HashSet (java.util.HashSet)13 Map (java.util.Map)13 Set (java.util.Set)13 Collectors (java.util.stream.Collectors)13 Test (org.junit.Test)13 Mockito.verify (org.mockito.Mockito.verify)13 Collections (java.util.Collections)12 Arrays.asList (java.util.Arrays.asList)11 IOException (java.io.IOException)10 Arrays (java.util.Arrays)10 Collections.emptySet (java.util.Collections.emptySet)10 Collections.singleton (java.util.Collections.singleton)10 Collections.singletonMap (java.util.Collections.singletonMap)10 Function (java.util.function.Function)10