Search in sources :

Example 71 with Mock

use of org.mockito.Mock in project che by eclipse.

the class TestServiceClientTest method initMocks.

@Before
public void initMocks() {
    MockitoAnnotations.initMocks(this);
    testServiceClient = spy(new TestServiceClient(appContext, asyncRequestFactory, dtoUnmarshallerFactory, dtoFactory, commandManager, execAgentCommandManager, promiseProvider, macroProcessor, commandConsoleFactory, processesPanelPresenter));
    doReturn(new PromiseMocker<TestResult>().getPromise()).when(testServiceClient).sendTests(anyString(), anyString(), anyMapOf(String.class, String.class));
    doAnswer(new FunctionAnswer<Executor.ExecutorBody<TestResult>, Promise<TestResult>>(executorBody -> {
        ExecutorPromiseMocker<TestResult> mocker = new ExecutorPromiseMocker<TestResult>(executorBody, (testResult, thisMocker) -> {
            thisMocker.applyOnThenOperation(testResult);
            return null;
        }, (promiseError, thisMocker) -> {
            thisMocker.applyOnCatchErrorOperation(promiseError);
            return null;
        });
        executorBody.apply(mocker.getResolveFunction(), mocker.getRejectFunction());
        return mocker.getPromise();
    })).when(testServiceClient).promiseFromExecutorBody(Matchers.<Executor.ExecutorBody<TestResult>>any());
    doAnswer(new FunctionAnswer<Throwable, PromiseError>(throwable -> {
        PromiseError promiseError = mock(PromiseError.class);
        when(promiseError.getCause()).thenReturn(throwable);
        return promiseError;
    })).when(testServiceClient).promiseFromThrowable(any(Throwable.class));
    when(appContext.getDevMachine()).thenReturn(devMachine);
    when(machine.getId()).thenReturn("DevMachineId");
    doAnswer(new FunctionAnswer<String, Promise<String>>(commandLine -> {
        String processedCommandLine = commandLine.replace("${current.project.path}", rootOfProjects + "/" + projectPath);
        return new PromiseMocker<String>().applyOnThenOperation(processedCommandLine).getPromise();
    })).when(macroProcessor).expandMacros(anyString());
    when(commandConsoleFactory.create(any(CommandImpl.class), any(Machine.class))).then(createCall -> {
        CommandOutputConsole commandOutputConsole = mock(CommandOutputConsole.class);
        when(commandOutputConsole.getProcessStartedOperation()).thenReturn(processStartedEvent -> {
            consoleEvents.add(processStartedEvent);
        });
        when(commandOutputConsole.getProcessDiedOperation()).thenReturn(processDiedEvent -> {
            consoleEvents.add(processDiedEvent);
        });
        when(commandOutputConsole.getStdErrOperation()).thenReturn(processStdErrEvent -> {
            consoleEvents.add(processStdErrEvent);
        });
        when(commandOutputConsole.getStdOutOperation()).thenReturn(processStdOutEvent -> {
            consoleEvents.add(processStdOutEvent);
        });
        return commandOutputConsole;
    });
    consoleEvents.clear();
    when(execAgentCommandManager.startProcess(anyString(), any(Command.class))).then(startProcessCall -> {
        @SuppressWarnings("unchecked") ExecAgentPromise<ProcessStartResponseDto> execAgentPromise = (ExecAgentPromise<ProcessStartResponseDto>) mock(ExecAgentPromise.class);
        class ProcessEventForward<DtoType> extends FunctionAnswer<Operation<DtoType>, ExecAgentPromise<ProcessStartResponseDto>> {

            public ProcessEventForward(Class<DtoType> dtoClass) {
                super(new java.util.function.Function<Operation<DtoType>, ExecAgentPromise<ProcessStartResponseDto>>() {

                    @Override
                    public ExecAgentPromise<ProcessStartResponseDto> apply(Operation<DtoType> op) {
                        operationsOnProcessEvents.put(dtoClass, op);
                        return execAgentPromise;
                    }
                });
            }
        }
        when(execAgentPromise.then(any())).then(new ProcessEventForward<>(ProcessStartResponseDto.class));
        when(execAgentPromise.thenIfProcessStartedEvent(any())).then(new ProcessEventForward<>(ProcessStartedEventDto.class));
        when(execAgentPromise.thenIfProcessDiedEvent(any())).then(new ProcessEventForward<>(ProcessDiedEventDto.class));
        when(execAgentPromise.thenIfProcessStdErrEvent(any())).then(new ProcessEventForward<>(ProcessStdErrEventDto.class));
        when(execAgentPromise.thenIfProcessStdOutEvent(any())).then(new ProcessEventForward<>(ProcessStdOutEventDto.class));
        return execAgentPromise;
    });
    operationsOnProcessEvents.clear();
}
Also used : Arrays(java.util.Arrays) AsyncRequestFactory(org.eclipse.che.ide.rest.AsyncRequestFactory) ProcessStartedEventDto(org.eclipse.che.api.machine.shared.dto.execagent.event.ProcessStartedEventDto) Executor(org.eclipse.che.api.promises.client.js.Executor) PromiseError(org.eclipse.che.api.promises.client.PromiseError) MockitoAnnotations(org.mockito.MockitoAnnotations) Arrays.asList(java.util.Arrays.asList) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) Spy(org.mockito.Spy) Mockito.doReturn(org.mockito.Mockito.doReturn) Operation(org.eclipse.che.api.promises.client.Operation) CommandConsoleFactory(org.eclipse.che.ide.extension.machine.client.outputspanel.console.CommandConsoleFactory) DtoUnmarshallerFactory(org.eclipse.che.ide.rest.DtoUnmarshallerFactory) OperationException(org.eclipse.che.api.promises.client.OperationException) StatusNotification(org.eclipse.che.ide.api.notification.StatusNotification) DevMachine(org.eclipse.che.ide.api.machine.DevMachine) Collectors(java.util.stream.Collectors) Matchers.any(org.mockito.Matchers.any) List(java.util.List) ProcessStartResponseDto(org.eclipse.che.api.machine.shared.dto.execagent.ProcessStartResponseDto) Mockito.mock(org.mockito.Mockito.mock) Command(org.eclipse.che.api.core.model.machine.Command) ProcessStdOutEventDto(org.eclipse.che.api.machine.shared.dto.execagent.event.ProcessStdOutEventDto) CommandManager(org.eclipse.che.ide.api.command.CommandManager) GwtMockitoTestRunner(com.google.gwtmockito.GwtMockitoTestRunner) CommandOutputConsole(org.eclipse.che.ide.extension.machine.client.outputspanel.console.CommandOutputConsole) Matchers(org.mockito.Matchers) Mock(org.mockito.Mock) CommandImpl(org.eclipse.che.ide.api.command.CommandImpl) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) Matchers.anyString(org.mockito.Matchers.anyString) ProcessDiedEventDto(org.eclipse.che.api.machine.shared.dto.execagent.event.ProcessDiedEventDto) ArrayList(java.util.ArrayList) Promise(org.eclipse.che.api.promises.client.Promise) Matchers.anyMapOf(org.mockito.Matchers.anyMapOf) ProcessStdErrEventDto(org.eclipse.che.api.machine.shared.dto.execagent.event.ProcessStdErrEventDto) AppContext(org.eclipse.che.ide.api.app.AppContext) Before(org.junit.Before) DtoFactory(org.eclipse.che.ide.dto.DtoFactory) DtoWithPid(org.eclipse.che.api.machine.shared.dto.execagent.event.DtoWithPid) PromiseProvider(org.eclipse.che.api.promises.client.PromiseProvider) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Machine(org.eclipse.che.api.core.model.machine.Machine) ExecAgentCommandManager(org.eclipse.che.ide.api.machine.ExecAgentCommandManager) Mockito.never(org.mockito.Mockito.never) ExecAgentPromise(org.eclipse.che.ide.api.machine.execagent.ExecAgentPromise) TestResult(org.eclipse.che.api.testing.shared.TestResult) Assert(org.junit.Assert) Collections(java.util.Collections) MacroProcessor(org.eclipse.che.ide.api.macro.MacroProcessor) ProcessesPanelPresenter(org.eclipse.che.ide.extension.machine.client.processes.panel.ProcessesPanelPresenter) ProcessStdErrEventDto(org.eclipse.che.api.machine.shared.dto.execagent.event.ProcessStdErrEventDto) Matchers.anyString(org.mockito.Matchers.anyString) Operation(org.eclipse.che.api.promises.client.Operation) DevMachine(org.eclipse.che.ide.api.machine.DevMachine) Machine(org.eclipse.che.api.core.model.machine.Machine) ExecAgentPromise(org.eclipse.che.ide.api.machine.execagent.ExecAgentPromise) Executor(org.eclipse.che.api.promises.client.js.Executor) CommandOutputConsole(org.eclipse.che.ide.extension.machine.client.outputspanel.console.CommandOutputConsole) ProcessStdOutEventDto(org.eclipse.che.api.machine.shared.dto.execagent.event.ProcessStdOutEventDto) CommandImpl(org.eclipse.che.ide.api.command.CommandImpl) TestResult(org.eclipse.che.api.testing.shared.TestResult) ProcessDiedEventDto(org.eclipse.che.api.machine.shared.dto.execagent.event.ProcessDiedEventDto) ProcessStartResponseDto(org.eclipse.che.api.machine.shared.dto.execagent.ProcessStartResponseDto) Promise(org.eclipse.che.api.promises.client.Promise) ExecAgentPromise(org.eclipse.che.ide.api.machine.execagent.ExecAgentPromise) PromiseError(org.eclipse.che.api.promises.client.PromiseError) Command(org.eclipse.che.api.core.model.machine.Command) ProcessStartedEventDto(org.eclipse.che.api.machine.shared.dto.execagent.event.ProcessStartedEventDto) Before(org.junit.Before)

Example 72 with Mock

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

the class NotificationTimerTaskTest method testLimit24h.

@Test
public void testLimit24h() {
    when(notificationTime.get()).thenReturn(ZonedDateTime.now().minusDays(30));
    // return one notification for our project
    SonarQubeNotification notif = mock(SonarQubeNotification.class);
    when(notif.projectKey()).thenReturn("myproject");
    when(notificationChecker.request(anyMap())).thenReturn(Collections.singletonList(notif));
    // execute with one project
    NotificationConfiguration project = createProject("myproject");
    timerTask.setProjects(Collections.singleton(project));
    timerTask.run();
    // verify checker used once and notification was returned through the listener
    verify(notificationCheckerFactory, times(1)).create(any(ServerConfiguration.class));
    verify(notificationChecker).request(ArgumentMatchers.argThat(map -> {
        ZonedDateTime time = map.values().iterator().next();
        return time.isAfter(ZonedDateTime.now().minusHours(25)) && time.isBefore(ZonedDateTime.now().minusHours(23));
    }));
    verify(listener).handle(notif);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers(org.mockito.ArgumentMatchers) Mock(org.mockito.Mock) LastNotificationTime(org.sonarsource.sonarlint.core.client.api.notifications.LastNotificationTime) ZonedDateTime(java.time.ZonedDateTime) SonarQubeNotification(org.sonarsource.sonarlint.core.client.api.notifications.SonarQubeNotification) ArgumentMatchers.anyMap(org.mockito.ArgumentMatchers.anyMap) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) ServerConfiguration(org.sonarsource.sonarlint.core.client.api.connected.ServerConfiguration) SonarQubeNotificationListener(org.sonarsource.sonarlint.core.client.api.notifications.SonarQubeNotificationListener) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) MockitoAnnotations(org.mockito.MockitoAnnotations) NotificationConfiguration(org.sonarsource.sonarlint.core.client.api.common.NotificationConfiguration) Collections(java.util.Collections) Mockito.mock(org.mockito.Mockito.mock) Before(org.junit.Before) ZonedDateTime(java.time.ZonedDateTime) SonarQubeNotification(org.sonarsource.sonarlint.core.client.api.notifications.SonarQubeNotification) ServerConfiguration(org.sonarsource.sonarlint.core.client.api.connected.ServerConfiguration) NotificationConfiguration(org.sonarsource.sonarlint.core.client.api.common.NotificationConfiguration) Test(org.junit.Test)

Example 73 with Mock

use of org.mockito.Mock in project ORCID-Source by ORCID.

the class NotificationManagerTest method testFindPermissionsByOrcidAndClient.

/**
 * Test independent of spring context, sets up NotificationManager with
 * mocked notifiation dao and notification adapter
 */
@Test
public void testFindPermissionsByOrcidAndClient() {
    List<Notification> notificationPermissions = IntStream.range(0, 10).mapToObj(i -> new NotificationPermission()).collect(Collectors.toList());
    NotificationDao notificationDao = mock(NotificationDaoImpl.class);
    JpaJaxbNotificationAdapter adapter = mock(JpaJaxbNotificationAdapterImpl.class);
    when(notificationDao.findPermissionsByOrcidAndClient(anyString(), anyString(), anyInt(), anyInt())).thenReturn(new ArrayList<NotificationEntity>());
    when(adapter.toNotification(Matchers.<ArrayList<NotificationEntity>>any())).thenReturn(notificationPermissions);
    NotificationManager notificationManager = new NotificationManagerImpl();
    ReflectionTestUtils.setField(notificationManager, "notificationAdapter", adapter);
    ReflectionTestUtils.setField(notificationManager, "notificationDao", notificationDao);
    NotificationPermissions notifications = notificationManager.findPermissionsByOrcidAndClient("some-orcid", "some-client", 0, OrcidApiConstants.MAX_NOTIFICATIONS_AVAILABLE);
    assertEquals(notificationPermissions.size(), notifications.getNotifications().size());
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Arrays(java.util.Arrays) TargetProxyHelper(org.orcid.test.TargetProxyHelper) OrcidJUnit4ClassRunner(org.orcid.test.OrcidJUnit4ClassRunner) URISyntaxException(java.net.URISyntaxException) ProfileEventEntity(org.orcid.persistence.jpa.entities.ProfileEventEntity) NotificationPermissions(org.orcid.jaxb.model.notification.permission_v2.NotificationPermissions) NotificationPermission(org.orcid.jaxb.model.notification.permission_v2.NotificationPermission) RecordNameEntity(org.orcid.persistence.jpa.entities.RecordNameEntity) DBUnitTest(org.orcid.test.DBUnitTest) Assert.assertThat(org.junit.Assert.assertThat) MockitoAnnotations(org.mockito.MockitoAnnotations) AmendedSection(org.orcid.jaxb.model.notification.amended_v2.AmendedSection) ProfileDao(org.orcid.persistence.dao.ProfileDao) Source(org.orcid.jaxb.model.common_v2.Source) NotificationDao(org.orcid.persistence.dao.NotificationDao) After(org.junit.After) NotificationManagerImpl(org.orcid.core.manager.impl.NotificationManagerImpl) NotificationType(org.orcid.jaxb.model.notification_v2.NotificationType) AfterClass(org.junit.AfterClass) OrcidProfile(org.orcid.jaxb.model.message.OrcidProfile) Resource(javax.annotation.Resource) OrcidOauth2TokenDetailService(org.orcid.core.oauth.OrcidOauth2TokenDetailService) ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) Set(java.util.Set) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) NotificationEntity(org.orcid.persistence.jpa.entities.NotificationEntity) List(java.util.List) EmailEntity(org.orcid.persistence.jpa.entities.EmailEntity) NotificationDaoImpl(org.orcid.persistence.dao.impl.NotificationDaoImpl) GenericDao(org.orcid.persistence.dao.GenericDao) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IntStream(java.util.stream.IntStream) Notification(org.orcid.jaxb.model.notification_v2.Notification) NotificationCustomEntity(org.orcid.persistence.jpa.entities.NotificationCustomEntity) CoreMatchers.anyOf(org.hamcrest.CoreMatchers.anyOf) BeforeClass(org.junit.BeforeClass) Matchers(org.mockito.Matchers) Mock(org.mockito.Mock) CoreMatchers.not(org.hamcrest.CoreMatchers.not) RunWith(org.junit.runner.RunWith) MailGunManager(org.orcid.core.manager.impl.MailGunManager) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) NotificationAmended(org.orcid.jaxb.model.notification.amended_v2.NotificationAmended) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Locale(org.orcid.jaxb.model.common_v2.Locale) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) JAXBContext(javax.xml.bind.JAXBContext) IntFunction(java.util.function.IntFunction) Before(org.junit.Before) Unmarshaller(javax.xml.bind.Unmarshaller) SourceEntity(org.orcid.persistence.jpa.entities.SourceEntity) OrcidMessage(org.orcid.jaxb.model.message.OrcidMessage) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Test(org.junit.Test) ClientDetailsDao(org.orcid.persistence.dao.ClientDetailsDao) Mockito.when(org.mockito.Mockito.when) JpaJaxbNotificationAdapterImpl(org.orcid.core.adapter.impl.JpaJaxbNotificationAdapterImpl) NotificationInstitutionalConnection(org.orcid.model.notification.institutional_sign_in_v2.NotificationInstitutionalConnection) OrcidApiConstants(org.orcid.core.api.OrcidApiConstants) Mockito.verify(org.mockito.Mockito.verify) NotificationCustom(org.orcid.jaxb.model.notification.custom_v2.NotificationCustom) Mockito(org.mockito.Mockito) Visibility(org.orcid.jaxb.model.common_v2.Visibility) Mockito.never(org.mockito.Mockito.never) JpaJaxbNotificationAdapter(org.orcid.core.adapter.JpaJaxbNotificationAdapter) ContextConfiguration(org.springframework.test.context.ContextConfiguration) SecurityQuestionEntity(org.orcid.persistence.jpa.entities.SecurityQuestionEntity) Email(org.orcid.jaxb.model.record_v2.Email) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Transactional(org.springframework.transaction.annotation.Transactional) NotificationDao(org.orcid.persistence.dao.NotificationDao) JpaJaxbNotificationAdapter(org.orcid.core.adapter.JpaJaxbNotificationAdapter) NotificationPermissions(org.orcid.jaxb.model.notification.permission_v2.NotificationPermissions) NotificationPermission(org.orcid.jaxb.model.notification.permission_v2.NotificationPermission) NotificationEntity(org.orcid.persistence.jpa.entities.NotificationEntity) Notification(org.orcid.jaxb.model.notification_v2.Notification) NotificationManagerImpl(org.orcid.core.manager.impl.NotificationManagerImpl) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Example 74 with Mock

use of org.mockito.Mock in project ORCID-Source by ORCID.

the class NotificationManagerTest method testFindPermissionsByOrcidAndClient.

/**
 * Test independent of spring context, sets up NotificationManager with
 * mocked notifiation dao and notification adapter
 */
@Test
public void testFindPermissionsByOrcidAndClient() {
    List<Notification> notificationPermissions = IntStream.range(0, 10).mapToObj(i -> new NotificationPermission()).collect(Collectors.toList());
    NotificationDao notificationDao = mock(NotificationDaoImpl.class);
    JpaJaxbNotificationAdapter adapter = mock(JpaJaxbNotificationAdapterImpl.class);
    when(notificationDao.findPermissionsByOrcidAndClient(anyString(), anyString(), anyInt(), anyInt())).thenReturn(new ArrayList<NotificationEntity>());
    when(adapter.toNotification(Matchers.<ArrayList<NotificationEntity>>any())).thenReturn(notificationPermissions);
    NotificationManager notificationManager = new NotificationManagerImpl();
    ReflectionTestUtils.setField(notificationManager, "notificationAdapter", adapter);
    ReflectionTestUtils.setField(notificationManager, "notificationDao", notificationDao);
    NotificationPermissions notifications = notificationManager.findPermissionsByOrcidAndClient("some-orcid", "some-client", 0, OrcidApiConstants.MAX_NOTIFICATIONS_AVAILABLE);
    assertEquals(notificationPermissions.size(), notifications.getNotifications().size());
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Notification(org.orcid.jaxb.model.v3.dev1.notification.Notification) Arrays(java.util.Arrays) Locale(org.orcid.jaxb.model.v3.dev1.common.Locale) TargetProxyHelper(org.orcid.test.TargetProxyHelper) Date(java.util.Date) OrcidJUnit4ClassRunner(org.orcid.test.OrcidJUnit4ClassRunner) URISyntaxException(java.net.URISyntaxException) ProfileEventEntity(org.orcid.persistence.jpa.entities.ProfileEventEntity) RecordNameEntity(org.orcid.persistence.jpa.entities.RecordNameEntity) DBUnitTest(org.orcid.test.DBUnitTest) Assert.assertThat(org.junit.Assert.assertThat) NotificationType(org.orcid.jaxb.model.v3.dev1.notification.NotificationType) MockitoAnnotations(org.mockito.MockitoAnnotations) Pair(org.apache.commons.lang3.tuple.Pair) ProfileDao(org.orcid.persistence.dao.ProfileDao) NotificationDao(org.orcid.persistence.dao.NotificationDao) After(org.junit.After) ProfileEntityCacheManager(org.orcid.core.manager.ProfileEntityCacheManager) NotificationInstitutionalConnection(org.orcid.model.v3.dev1.notification.institutional_sign_in.NotificationInstitutionalConnection) AfterClass(org.junit.AfterClass) OrcidProfile(org.orcid.jaxb.model.message.OrcidProfile) Resource(javax.annotation.Resource) EncryptionManager(org.orcid.core.manager.EncryptionManager) OrcidOauth2TokenDetailService(org.orcid.core.oauth.OrcidOauth2TokenDetailService) ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) Set(java.util.Set) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) NotificationEntity(org.orcid.persistence.jpa.entities.NotificationEntity) List(java.util.List) Email(org.orcid.jaxb.model.v3.dev1.record.Email) EmailEntity(org.orcid.persistence.jpa.entities.EmailEntity) Source(org.orcid.jaxb.model.v3.dev1.common.Source) JpaJaxbNotificationAdapterImpl(org.orcid.core.adapter.v3.impl.JpaJaxbNotificationAdapterImpl) NotificationDaoImpl(org.orcid.persistence.dao.impl.NotificationDaoImpl) GenericDao(org.orcid.persistence.dao.GenericDao) NotificationManagerImpl(org.orcid.core.manager.v3.impl.NotificationManagerImpl) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IntStream(java.util.stream.IntStream) NotificationCustomEntity(org.orcid.persistence.jpa.entities.NotificationCustomEntity) CoreMatchers.anyOf(org.hamcrest.CoreMatchers.anyOf) BeforeClass(org.junit.BeforeClass) NotificationPermissions(org.orcid.jaxb.model.v3.dev1.notification.permission.NotificationPermissions) Matchers(org.mockito.Matchers) Mock(org.mockito.Mock) CoreMatchers.not(org.hamcrest.CoreMatchers.not) RunWith(org.junit.runner.RunWith) ArrayUtils(org.apache.commons.lang3.ArrayUtils) NotificationPermission(org.orcid.jaxb.model.v3.dev1.notification.permission.NotificationPermission) MailGunManager(org.orcid.core.manager.impl.MailGunManager) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) NotificationCustom(org.orcid.jaxb.model.v3.dev1.notification.custom.NotificationCustom) EmailEventEntity(org.orcid.persistence.jpa.entities.EmailEventEntity) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) JAXBContext(javax.xml.bind.JAXBContext) IntFunction(java.util.function.IntFunction) Before(org.junit.Before) Unmarshaller(javax.xml.bind.Unmarshaller) SourceEntity(org.orcid.persistence.jpa.entities.SourceEntity) CollectionUtils(org.springframework.cglib.core.CollectionUtils) OrcidMessage(org.orcid.jaxb.model.message.OrcidMessage) Assert.assertNotNull(org.junit.Assert.assertNotNull) AmendedSection(org.orcid.jaxb.model.v3.dev1.notification.amended.AmendedSection) Assert.assertTrue(org.junit.Assert.assertTrue) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Test(org.junit.Test) ClientDetailsDao(org.orcid.persistence.dao.ClientDetailsDao) Mockito.when(org.mockito.Mockito.when) LocalDateTime(org.joda.time.LocalDateTime) OrcidApiConstants(org.orcid.core.api.OrcidApiConstants) Mockito.verify(org.mockito.Mockito.verify) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) EmailEventType(org.orcid.persistence.jpa.entities.EmailEventType) ContextConfiguration(org.springframework.test.context.ContextConfiguration) SecurityQuestionEntity(org.orcid.persistence.jpa.entities.SecurityQuestionEntity) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) JpaJaxbNotificationAdapter(org.orcid.core.adapter.v3.JpaJaxbNotificationAdapter) Transactional(org.springframework.transaction.annotation.Transactional) NotificationDao(org.orcid.persistence.dao.NotificationDao) JpaJaxbNotificationAdapter(org.orcid.core.adapter.v3.JpaJaxbNotificationAdapter) NotificationPermissions(org.orcid.jaxb.model.v3.dev1.notification.permission.NotificationPermissions) NotificationPermission(org.orcid.jaxb.model.v3.dev1.notification.permission.NotificationPermission) NotificationEntity(org.orcid.persistence.jpa.entities.NotificationEntity) Notification(org.orcid.jaxb.model.v3.dev1.notification.Notification) NotificationManagerImpl(org.orcid.core.manager.v3.impl.NotificationManagerImpl) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Example 75 with Mock

use of org.mockito.Mock in project google-cloud-intellij by GoogleCloudPlatform.

the class GoogleApiClientAppEngineAdminServiceTest method testCreateApplication.

@Test
public void testCreateApplication() throws IOException, GoogleApiException {
    String operationId = "my-operation-id";
    String operationName = "apps/-/operations/" + operationId;
    Operation inProgressOperation = buildInProgressOperation(operationName);
    when(appengineClientMock.getAppsCreateQuery().execute()).thenReturn(inProgressOperation);
    final String locationId = "us-east1";
    final String projectId = "my-project";
    Map<String, Object> response = new HashMap<>();
    response.put("name", projectId);
    response.put("locationId", locationId);
    Operation doneOperation = new Operation();
    doneOperation.setName(operationName);
    doneOperation.setDone(true);
    doneOperation.setResponse(response);
    // require polling several times
    when(appengineClientMock.getAppsOperationsGetQuery().execute()).thenReturn(inProgressOperation).thenReturn(inProgressOperation).thenReturn(doneOperation);
    Application result = service.createApplication(locationId, projectId, mock(Credential.class));
    // ensure the 'getOperation' API call(s) were made correctly
    verify(appengineClientMock.apps().operations(), atLeastOnce()).get(eq(projectId), eq(operationId));
    // ensure the 'createApplication' API call was made with the correct args
    verify(appengineClientMock.apps(), times(1)).create(argThat(application -> application.getId().equals(projectId) && application.getLocationId().equals(locationId)));
    // ensure the 'createApplication' API call was only made once
    verify(appengineClientMock.getAppsCreateQuery(), times(1)).execute();
    assertEquals(projectId, result.getName());
    assertEquals(locationId, result.getLocationId());
}
Also used : Assert.fail(junit.framework.Assert.fail) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Assert.assertEquals(junit.framework.Assert.assertEquals) Arrays(java.util.Arrays) Application(com.google.api.services.appengine.v1.model.Application) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Mock(org.mockito.Mock) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) ArrayList(java.util.ArrayList) Location(com.google.api.services.appengine.v1.model.Location) Mockito.doThrow(org.mockito.Mockito.doThrow) MockitoAnnotations(org.mockito.MockitoAnnotations) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) Credential(com.google.api.client.auth.oauth2.Credential) Before(org.junit.Before) AppEngineApplicationNotFoundException(com.google.cloud.tools.intellij.appengine.application.GoogleApiClientAppEngineAdminService.AppEngineApplicationNotFoundException) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) HttpTransport(com.google.api.client.http.HttpTransport) ListLocationsResponse(com.google.api.services.appengine.v1.model.ListLocationsResponse) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) GoogleApiClientFactory(com.google.cloud.tools.intellij.resources.GoogleApiClientFactory) Mockito.verify(org.mockito.Mockito.verify) Operation(com.google.api.services.appengine.v1.model.Operation) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) JsonFactory(com.google.api.client.json.JsonFactory) Appengine(com.google.api.services.appengine.v1.Appengine) Status(com.google.api.services.appengine.v1.model.Status) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) BasePluginTestCase(com.google.cloud.tools.intellij.testing.BasePluginTestCase) Credential(com.google.api.client.auth.oauth2.Credential) HashMap(java.util.HashMap) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Operation(com.google.api.services.appengine.v1.model.Operation) Application(com.google.api.services.appengine.v1.model.Application) Test(org.junit.Test)

Aggregations

Mock (org.mockito.Mock)135 Mockito.mock (org.mockito.Mockito.mock)109 Test (org.junit.Test)104 Before (org.junit.Before)96 Mockito.verify (org.mockito.Mockito.verify)89 Mockito.when (org.mockito.Mockito.when)82 List (java.util.List)81 RunWith (org.junit.runner.RunWith)76 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)65 Collections (java.util.Collections)56 ArrayList (java.util.ArrayList)55 ArgumentCaptor (org.mockito.ArgumentCaptor)52 Mockito.spy (org.mockito.Mockito.spy)48 Arrays (java.util.Arrays)44 Assert.assertEquals (org.junit.Assert.assertEquals)41 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)41 Mockito.doReturn (org.mockito.Mockito.doReturn)41 Map (java.util.Map)40 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)38 Mockito.never (org.mockito.Mockito.never)37