Search in sources :

Example 41 with Mock

use of org.mockito.Mock in project CzechIdMng by bcvsolutions.

the class RemoveRoleCompositionTaskExecutorIntegrationTest method testRemoveAssignedRolesWithExceptionOnEnd.

@Test
public void testRemoveAssignedRolesWithExceptionOnEnd() {
    // prepare role composition
    IdmRoleDto superior = getHelper().createRole();
    IdmRoleDto subOne = getHelper().createRole();
    IdmRoleDto subOneSub = getHelper().createRole();
    getHelper().createRoleComposition(superior, subOne);
    IdmRoleCompositionDto subOneSubRoleComposition = getHelper().createRoleComposition(subOne, subOneSub);
    // 
    // assign superior role
    IdmIdentityDto identity = getHelper().createIdentity();
    getHelper().createIdentityRole(identity, superior);
    // 
    List<IdmIdentityRoleDto> assignedRoles = identityRoleService.findAllByIdentity(identity.getId());
    Assert.assertEquals(3, assignedRoles.size());
    Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getRole().equals(superior.getId())));
    Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getRole().equals(subOne.getId())));
    Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getRole().equals(subOneSub.getId())));
    // 
    // remove role composition by task with mock service => we want to throw exception
    Mockito.when(mockIdentityRoleService.count(ArgumentMatchers.any(IdmIdentityRoleFilter.class))).thenReturn(1L);
    Mockito.when(mockIdentityRoleService.find(ArgumentMatchers.any(IdmIdentityRoleFilter.class), ArgumentMatchers.isNull())).then(new AssignedRolesAnswer(subOneSubRoleComposition.getId()));
    RemoveRoleCompositionTaskExecutor taskExecutor = new RemoveRoleCompositionTaskExecutor();
    AutowireHelper.autowire(taskExecutor);
    IdmLongRunningTaskDto lrt = longRunningTaskManager.resolveLongRunningTask(taskExecutor, null, OperationState.RUNNING);
    UUID taskId = lrt.getId();
    taskExecutor.setIdentityRoleService(mockIdentityRoleService);
    taskExecutor.setRoleCompositionId(subOneSubRoleComposition.getId());
    // 
    try {
        getHelper().setConfigurationValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_ENABLED, true);
        taskExecutor.call();
        getHelper().waitForResult(res -> {
            return longRunningTaskManager.getLongRunningTask(taskId).getResultState().isRunnable();
        });
    } finally {
        getHelper().setConfigurationValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_ENABLED, false);
    }
    // 
    // long running task has a proper state with exception
    lrt = longRunningTaskManager.getLongRunningTask(lrt.getId());
    Assert.assertEquals(OperationState.EXCEPTION, lrt.getResultState());
    Assert.assertEquals(CoreResultCode.ROLE_COMPOSITION_REMOVE_HAS_ASSIGNED_ROLES.name(), lrt.getResult().getCode());
    // 
    // start event is ended
    IdmEntityEventFilter eventFilter = new IdmEntityEventFilter();
    eventFilter.setTransactionId(lrt.getTransactionId());
    eventFilter.setEventType(LongRunningTaskEventType.START.name());
    List<IdmEntityEventDto> startEvents = entityEventManager.findEvents(eventFilter, null).getContent();
    Assert.assertEquals(1, startEvents.size());
    Assert.assertEquals(OperationState.EXECUTED, startEvents.get(0).getResult().getState());
    // 
    // business role still exists
    Assert.assertNotNull(roleCompositionService.get(subOneSubRoleComposition));
    // 
    // but assigned roles should be removed
    assignedRoles = identityRoleService.findAllByIdentity(identity.getId());
    Assert.assertEquals(2, assignedRoles.size());
    Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getRole().equals(superior.getId())));
    Assert.assertTrue(assignedRoles.stream().anyMatch(ir -> ir.getRole().equals(subOne.getId())));
}
Also used : ArgumentMatchers(org.mockito.ArgumentMatchers) IdmEntityEventDto(eu.bcvsolutions.idm.core.api.dto.IdmEntityEventDto) Mock(org.mockito.Mock) IdmIdentityRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto) IdmRoleCompositionDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleCompositionDto) Autowired(org.springframework.beans.factory.annotation.Autowired) AutowireHelper(eu.bcvsolutions.idm.core.api.utils.AutowireHelper) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Lists(com.google.common.collect.Lists) AbstractIntegrationTest(eu.bcvsolutions.idm.test.api.AbstractIntegrationTest) LongRunningTaskEventType(eu.bcvsolutions.idm.core.scheduler.api.event.LongRunningTaskEvent.LongRunningTaskEventType) IdmIdentityRoleService(eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService) IdmIdentityRoleFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter) LongRunningTaskManager(eu.bcvsolutions.idm.core.scheduler.api.service.LongRunningTaskManager) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) IdmEntityEventFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmEntityEventFilter) PageRequest(org.springframework.data.domain.PageRequest) OperationState(eu.bcvsolutions.idm.core.api.domain.OperationState) Test(org.junit.Test) IdmRoleCompositionService(eu.bcvsolutions.idm.core.api.service.IdmRoleCompositionService) UUID(java.util.UUID) Page(org.springframework.data.domain.Page) Mockito(org.mockito.Mockito) List(java.util.List) EventConfiguration(eu.bcvsolutions.idm.core.api.config.domain.EventConfiguration) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) IdmLongRunningTaskDto(eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) Assert(org.junit.Assert) PageImpl(org.springframework.data.domain.PageImpl) EntityEventManager(eu.bcvsolutions.idm.core.api.service.EntityEventManager) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) IdmLongRunningTaskDto(eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto) IdmIdentityRoleFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter) IdmRoleCompositionDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleCompositionDto) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) IdmIdentityRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto) UUID(java.util.UUID) IdmEntityEventFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmEntityEventFilter) IdmEntityEventDto(eu.bcvsolutions.idm.core.api.dto.IdmEntityEventDto) AbstractIntegrationTest(eu.bcvsolutions.idm.test.api.AbstractIntegrationTest) Test(org.junit.Test)

Example 42 with Mock

use of org.mockito.Mock in project pravega by pravega.

the class FlowHandlerTest method testHelloWithErrorReplyProcessor.

@Test
public void testHelloWithErrorReplyProcessor() throws Exception {
    ReplyProcessor errorProcessor = mock(ReplyProcessor.class);
    @Cleanup ClientConnection connection1 = flowHandler.createFlow(new Flow(11, 0), errorProcessor);
    @Cleanup ClientConnection connection2 = flowHandler.createFlow(flow, processor);
    doAnswer((Answer<Void>) invocation -> {
        throw new RuntimeException("Reply processor error");
    }).when(errorProcessor).hello(any(WireCommands.Hello.class));
    final WireCommands.Hello msg = new WireCommands.Hello(5, 4);
    flowHandler.process(msg);
    verify(processor).hello(msg);
    verify(errorProcessor).hello(msg);
}
Also used : Cleanup(lombok.Cleanup) KeepAliveTask(io.pravega.client.connection.impl.FlowHandler.KeepAliveTask) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) FailingReplyProcessor(io.pravega.shared.protocol.netty.FailingReplyProcessor) ChannelPromise(io.netty.channel.ChannelPromise) After(org.junit.After) Mockito.doAnswer(org.mockito.Mockito.doAnswer) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) AssertExtensions.assertThrows(io.pravega.test.common.AssertExtensions.assertThrows) UUID(java.util.UUID) Mockito.inOrder(org.mockito.Mockito.inOrder) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) ReplyProcessor(io.pravega.shared.protocol.netty.ReplyProcessor) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ObjectClosedException(io.pravega.common.ObjectClosedException) BeforeClass(org.junit.BeforeClass) Mock(org.mockito.Mock) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Reply(io.pravega.shared.protocol.netty.Reply) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Append(io.pravega.shared.protocol.netty.Append) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ByteBuf(io.netty.buffer.ByteBuf) MetricNotifier(io.pravega.shared.metrics.MetricNotifier) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Timeout(org.junit.rules.Timeout) KeepAlive(io.pravega.shared.protocol.netty.WireCommands.KeepAlive) ClientMetricKeys(io.pravega.shared.metrics.ClientMetricKeys) Before(org.junit.Before) InOrder(org.mockito.InOrder) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) WireCommands(io.pravega.shared.protocol.netty.WireCommands) ChannelFuture(io.netty.channel.ChannelFuture) Mockito.verify(org.mockito.Mockito.verify) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) String.valueOf(java.lang.String.valueOf) InlineExecutor(io.pravega.test.common.InlineExecutor) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) ClientConfig(io.pravega.client.ClientConfig) WireCommands(io.pravega.shared.protocol.netty.WireCommands) Cleanup(lombok.Cleanup) FailingReplyProcessor(io.pravega.shared.protocol.netty.FailingReplyProcessor) ReplyProcessor(io.pravega.shared.protocol.netty.ReplyProcessor) Test(org.junit.Test)

Example 43 with Mock

use of org.mockito.Mock in project sonarlint-core by SonarSource.

the class IssueExclusionsRegexpScannerTests method init.

@BeforeEach
void init() {
    MockitoAnnotations.initMocks(this);
    blockPatterns = Arrays.asList(new DoubleRegexpMatcher(Pattern.compile("// SONAR-OFF"), Pattern.compile("// SONAR-ON")), new DoubleRegexpMatcher(Pattern.compile("// FOO-OFF"), Pattern.compile("// FOO-ON")));
    allFilePatterns = Collections.singletonList(Pattern.compile("@SONAR-IGNORE-ALL"));
    javaFile = new SonarLintInputFile(new OnDiskTestClientInputFile(Paths.get("src/Foo.java"), "src/Foo.java", false, StandardCharsets.UTF_8), f -> mock(Metadata.class));
    regexpScanner = new IssueExclusionsRegexpScanner(javaFile, allFilePatterns, blockPatterns);
}
Also used : DoubleRegexpMatcher(org.sonarsource.sonarlint.core.analysis.container.analysis.issue.ignore.scanner.IssueExclusionsLoader.DoubleRegexpMatcher) SonarLintInputFile(org.sonarsource.sonarlint.core.analysis.container.analysis.filesystem.SonarLintInputFile) IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) FileMetadata(org.sonarsource.sonarlint.core.analysis.container.analysis.filesystem.FileMetadata) Metadata(org.sonarsource.sonarlint.core.analysis.container.analysis.filesystem.FileMetadata.Metadata) Arrays(java.util.Arrays) Files(java.nio.file.Files) Mock(org.mockito.Mock) UTF_8(java.nio.charset.StandardCharsets.UTF_8) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) IssueExclusionPatternInitializer(org.sonarsource.sonarlint.core.analysis.container.analysis.issue.ignore.pattern.IssueExclusionPatternInitializer) SonarLintInputFile(org.sonarsource.sonarlint.core.analysis.container.analysis.filesystem.SonarLintInputFile) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) MockitoAnnotations(org.mockito.MockitoAnnotations) List(java.util.List) Paths(java.nio.file.Paths) OnDiskTestClientInputFile(testutils.OnDiskTestClientInputFile) Pattern(java.util.regex.Pattern) DoubleRegexpMatcher(org.sonarsource.sonarlint.core.analysis.container.analysis.issue.ignore.scanner.IssueExclusionsLoader.DoubleRegexpMatcher) Path(java.nio.file.Path) Collections(java.util.Collections) AssertionsForClassTypes.assertThat(org.assertj.core.api.AssertionsForClassTypes.assertThat) Mockito.mock(org.mockito.Mockito.mock) OnDiskTestClientInputFile(testutils.OnDiskTestClientInputFile) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 44 with Mock

use of org.mockito.Mock in project kie-wb-common by kiegroup.

the class GeneralSettingsPresenterTest method testExecuteValidationFailing.

@Test
public void testExecuteValidationFailing() {
    final POM pom = mock(POM.class);
    doReturn(false).when(validationService).validate(eq(pom));
    generalSettingsPresenter.executeValidation(s -> s.validate(pom), "Test message").then(valid -> {
        Assert.fail("Promise should've been resolved!");
        return promises.resolve();
    }).catch_(e -> {
        verify(validationService).validate(eq(pom));
        Assert.assertEquals(e, "Test message");
        return promises.resolve();
    });
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) GAVPreferences(org.guvnor.common.services.project.preferences.GAVPreferences) CallerMock(org.uberfire.mocks.CallerMock) Mock(org.mockito.Mock) Promises(org.uberfire.client.promise.Promises) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) GAV(org.guvnor.common.services.project.model.GAV) RunWith(org.junit.runner.RunWith) PreferenceScopeResolutionStrategyInfo(org.uberfire.preferences.shared.impl.PreferenceScopeResolutionStrategyInfo) ProjectScopedResolutionStrategySupplier(org.guvnor.common.services.project.client.preferences.ProjectScopedResolutionStrategySupplier) Mockito.spy(org.mockito.Mockito.spy) SettingsSectionChange(org.kie.workbench.common.screens.library.client.settings.SettingsSectionChange) GitUrlsPresenter(org.kie.workbench.common.screens.library.client.settings.generalsettings.GitUrlsPresenter) LibraryPlaces(org.kie.workbench.common.screens.library.client.util.LibraryPlaces) POM(org.guvnor.common.services.project.model.POM) WorkspaceProject(org.guvnor.common.services.project.model.WorkspaceProject) SyncPromises(org.uberfire.promise.SyncPromises) Mockito.doReturn(org.mockito.Mockito.doReturn) Before(org.junit.Before) OrganizationalUnit(org.guvnor.structure.organizationalunit.OrganizationalUnit) ValidationService(org.kie.workbench.common.services.shared.validation.ValidationService) ProjectScreenModel(org.kie.workbench.common.screens.projecteditor.model.ProjectScreenModel) Test(org.junit.Test) Mockito.doNothing(org.mockito.Mockito.doNothing) Mockito.when(org.mockito.Mockito.when) WorkspaceProjectService(org.guvnor.common.services.project.service.WorkspaceProjectService) MenuItem(org.kie.workbench.common.screens.library.client.settings.util.sections.MenuItem) Mockito.verify(org.mockito.Mockito.verify) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) Caller(org.jboss.errai.common.client.api.Caller) EventSourceMock(org.uberfire.mocks.EventSourceMock) Assert(org.junit.Assert) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Mockito.mock(org.mockito.Mockito.mock) POM(org.guvnor.common.services.project.model.POM) Test(org.junit.Test)

Example 45 with Mock

use of org.mockito.Mock in project kie-wb-common by kiegroup.

the class GeneralSettingsPresenterTest method testExecuteValidation.

@Test
public void testExecuteValidation() {
    final POM pom = mock(POM.class);
    doReturn(true).when(validationService).validate(eq(pom));
    generalSettingsPresenter.executeValidation(s -> s.validate(pom), "Test message").then(valid -> {
        verify(validationService).validate(eq(pom));
        Assert.assertEquals(valid, true);
        return promises.resolve();
    }).catch_(e -> {
        Assert.fail("Promise should've been resolved!");
        return promises.resolve();
    });
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) GAVPreferences(org.guvnor.common.services.project.preferences.GAVPreferences) CallerMock(org.uberfire.mocks.CallerMock) Mock(org.mockito.Mock) Promises(org.uberfire.client.promise.Promises) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) GAV(org.guvnor.common.services.project.model.GAV) RunWith(org.junit.runner.RunWith) PreferenceScopeResolutionStrategyInfo(org.uberfire.preferences.shared.impl.PreferenceScopeResolutionStrategyInfo) ProjectScopedResolutionStrategySupplier(org.guvnor.common.services.project.client.preferences.ProjectScopedResolutionStrategySupplier) Mockito.spy(org.mockito.Mockito.spy) SettingsSectionChange(org.kie.workbench.common.screens.library.client.settings.SettingsSectionChange) GitUrlsPresenter(org.kie.workbench.common.screens.library.client.settings.generalsettings.GitUrlsPresenter) LibraryPlaces(org.kie.workbench.common.screens.library.client.util.LibraryPlaces) POM(org.guvnor.common.services.project.model.POM) WorkspaceProject(org.guvnor.common.services.project.model.WorkspaceProject) SyncPromises(org.uberfire.promise.SyncPromises) Mockito.doReturn(org.mockito.Mockito.doReturn) Before(org.junit.Before) OrganizationalUnit(org.guvnor.structure.organizationalunit.OrganizationalUnit) ValidationService(org.kie.workbench.common.services.shared.validation.ValidationService) ProjectScreenModel(org.kie.workbench.common.screens.projecteditor.model.ProjectScreenModel) Test(org.junit.Test) Mockito.doNothing(org.mockito.Mockito.doNothing) Mockito.when(org.mockito.Mockito.when) WorkspaceProjectService(org.guvnor.common.services.project.service.WorkspaceProjectService) MenuItem(org.kie.workbench.common.screens.library.client.settings.util.sections.MenuItem) Mockito.verify(org.mockito.Mockito.verify) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) Caller(org.jboss.errai.common.client.api.Caller) EventSourceMock(org.uberfire.mocks.EventSourceMock) Assert(org.junit.Assert) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Mockito.mock(org.mockito.Mockito.mock) POM(org.guvnor.common.services.project.model.POM) Test(org.junit.Test)

Aggregations

Mock (org.mockito.Mock)128 Mockito.mock (org.mockito.Mockito.mock)103 Test (org.junit.Test)98 Before (org.junit.Before)90 Mockito.verify (org.mockito.Mockito.verify)84 List (java.util.List)80 Mockito.when (org.mockito.Mockito.when)76 RunWith (org.junit.runner.RunWith)72 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)60 Collections (java.util.Collections)55 ArrayList (java.util.ArrayList)54 ArgumentCaptor (org.mockito.ArgumentCaptor)51 Mockito.spy (org.mockito.Mockito.spy)45 Arrays (java.util.Arrays)42 Assert.assertEquals (org.junit.Assert.assertEquals)40 Mockito.doReturn (org.mockito.Mockito.doReturn)40 Map (java.util.Map)38 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)38 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)37 Mockito.times (org.mockito.Mockito.times)36