Search in sources :

Example 66 with Answer

use of org.mockito.stubbing.Answer in project sonarqube by SonarSource.

the class QualityProfileEventsStepTest method verify_detection_with_complex_mix_of_qps.

@Test
public void verify_detection_with_complex_mix_of_qps() {
    final Set<Event> events = new HashSet<>();
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            events.add((Event) invocationOnMock.getArguments()[1]);
            return null;
        }
    }).when(eventRepository).add(eq(treeRootHolder.getRoot()), any(Event.class));
    mockMeasures(treeRootHolder.getRoot(), arrayOf(qp(QP_NAME_2, LANGUAGE_KEY_1), qp(QP_NAME_2, LANGUAGE_KEY_2), qp(QP_NAME_1, LANGUAGE_KEY_1, parseDateTime("2011-04-25T01:05:13+0100"))), arrayOf(qp(QP_NAME_1, LANGUAGE_KEY_1, parseDateTime("2011-04-25T01:05:17+0100")), qp(QP_NAME_2, LANGUAGE_KEY_2), qp(QP_NAME_2, LANGUAGE_KEY_3)));
    mockNoLanguageInRepository();
    underTest.execute();
    assertThat(events).extracting("name").containsOnly("Stop using '" + QP_NAME_2 + "' (" + LANGUAGE_KEY_1 + ")", "Use '" + QP_NAME_2 + "' (" + LANGUAGE_KEY_3 + ")", "Changes in '" + QP_NAME_1 + "' (" + LANGUAGE_KEY_1 + ")");
}
Also used : Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Event(org.sonar.server.computation.task.projectanalysis.event.Event) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 67 with Answer

use of org.mockito.stubbing.Answer in project sonarqube by SonarSource.

the class PluginDownloaderTest method before.

@Before
public void before() throws Exception {
    updateCenterMatrixFactory = mock(UpdateCenterMatrixFactory.class);
    updateCenter = mock(UpdateCenter.class);
    when(updateCenterMatrixFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.of(updateCenter));
    httpDownloader = mock(HttpDownloader.class);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock inv) throws Throwable {
            File toFile = (File) inv.getArguments()[1];
            touch(toFile);
            return null;
        }
    }).when(httpDownloader).download(any(URI.class), any(File.class));
    ServerFileSystem fs = mock(ServerFileSystem.class);
    downloadDir = testFolder.newFolder("downloads");
    when(fs.getDownloadedPluginsDir()).thenReturn(downloadDir);
    pluginDownloader = new PluginDownloader(updateCenterMatrixFactory, httpDownloader, fs);
}
Also used : ServerFileSystem(org.sonar.server.platform.ServerFileSystem) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) UpdateCenter(org.sonar.updatecenter.common.UpdateCenter) HttpDownloader(org.sonar.api.utils.HttpDownloader) InvocationOnMock(org.mockito.invocation.InvocationOnMock) File(java.io.File) URI(java.net.URI) Before(org.junit.Before)

Example 68 with Answer

use of org.mockito.stubbing.Answer in project neo4j by neo4j.

the class HighAvailabilityModeSwitcherTest method shouldRecognizeNewMasterIfNewMasterBecameAvailableDuringSwitch.

@Test
public void shouldRecognizeNewMasterIfNewMasterBecameAvailableDuringSwitch() throws Throwable {
    // When messages coming in the following ordering, the slave should detect that the master id has changed
    // M1: Get masterIsAvailable for instance 1 at PENDING state, changing PENDING -> TO_SLAVE
    // M2: Get masterIsAvailable for instance 2 at TO_SLAVE state, changing TO_SLAVE -> TO_SLAVE
    // Given
    final CountDownLatch firstMasterAvailableHandled = new CountDownLatch(1);
    final CountDownLatch secondMasterAvailableComes = new CountDownLatch(1);
    final CountDownLatch secondMasterAvailableHandled = new CountDownLatch(1);
    SwitchToSlaveCopyThenBranch switchToSlave = mock(SwitchToSlaveCopyThenBranch.class);
    HighAvailabilityModeSwitcher modeSwitcher = new HighAvailabilityModeSwitcher(switchToSlave, mock(SwitchToMaster.class), mock(Election.class), mock(ClusterMemberAvailability.class), mock(ClusterClient.class), mock(Supplier.class), new InstanceId(4), new ComponentSwitcherContainer(), neoStoreDataSourceSupplierMock(), NullLogService.getInstance()) {

        @Override
        ScheduledExecutorService createExecutor() {
            final ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
            final ExecutorService realExecutor = Executors.newSingleThreadExecutor();
            when(executor.submit(any(Runnable.class))).thenAnswer((Answer<Future<?>>) invocation -> realExecutor.submit((Runnable) () -> ((Runnable) invocation.getArguments()[0]).run()));
            when(executor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenAnswer((Answer<Future<?>>) invocation -> {
                realExecutor.submit((Callable<Void>) () -> {
                    firstMasterAvailableHandled.countDown();
                    secondMasterAvailableComes.await();
                    ((Runnable) invocation.getArguments()[0]).run();
                    secondMasterAvailableHandled.countDown();
                    return null;
                });
                return mock(ScheduledFuture.class);
            });
            return executor;
        }
    };
    modeSwitcher.init();
    modeSwitcher.start();
    modeSwitcher.listeningAt(URI.create("ha://server3?serverId=3"));
    // When
    // masterIsAvailable for instance 1
    URI uri1 = URI.create("ha://server1");
    // The first masterIsAvailable should fail so that the slave instance stops at TO_SLAVE state
    doThrow(new ComException("Fail to switch to slave and reschedule to retry")).when(switchToSlave).switchToSlave(any(LifeSupport.class), any(URI.class), eq(uri1), any(CancellationRequest.class));
    modeSwitcher.masterIsAvailable(new HighAvailabilityMemberChangeEvent(PENDING, TO_SLAVE, new InstanceId(1), uri1));
    // wait until the first masterIsAvailable triggers the exception handling
    firstMasterAvailableHandled.await();
    verify(switchToSlave).switchToSlave(any(LifeSupport.class), any(URI.class), eq(uri1), any(CancellationRequest.class));
    // masterIsAvailable for instance 2
    URI uri2 = URI.create("ha://server2");
    modeSwitcher.masterIsAvailable(new HighAvailabilityMemberChangeEvent(TO_SLAVE, TO_SLAVE, new InstanceId(2), uri2));
    secondMasterAvailableComes.countDown();
    // wait until switchToSlave method is invoked again
    secondMasterAvailableHandled.await();
    // Then
    // switchToSlave should be retried with new master id
    verify(switchToSlave).switchToSlave(any(LifeSupport.class), any(URI.class), eq(uri2), any(CancellationRequest.class));
}
Also used : InstanceId(org.neo4j.cluster.InstanceId) StoreId(org.neo4j.kernel.impl.store.StoreId) ScheduledFuture(java.util.concurrent.ScheduledFuture) NeoStoreDataSource(org.neo4j.kernel.NeoStoreDataSource) SwitchToMaster(org.neo4j.kernel.ha.cluster.SwitchToMaster) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TO_SLAVE(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberState.TO_SLAVE) Callable(java.util.concurrent.Callable) LifeSupport(org.neo4j.kernel.lifecycle.LifeSupport) NullLogProvider(org.neo4j.logging.NullLogProvider) Supplier(java.util.function.Supplier) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) Answer(org.mockito.stubbing.Answer) Mockito.doThrow(org.mockito.Mockito.doThrow) Future(java.util.concurrent.Future) PENDING(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberState.PENDING) AssertableLogProvider(org.neo4j.logging.AssertableLogProvider) Matchers.eq(org.mockito.Matchers.eq) CancellationRequest(org.neo4j.helpers.CancellationRequest) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Matchers.anyLong(org.mockito.Matchers.anyLong) URI(java.net.URI) MismatchingStoreIdException(org.neo4j.kernel.impl.store.MismatchingStoreIdException) ExecutorService(java.util.concurrent.ExecutorService) HighAvailabilityMemberState(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberState) InOrder(org.mockito.InOrder) ComException(org.neo4j.com.ComException) SwitchToSlaveCopyThenBranch(org.neo4j.kernel.ha.cluster.SwitchToSlaveCopyThenBranch) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) AssertableLogProvider.inLog(org.neo4j.logging.AssertableLogProvider.inLog) Election(org.neo4j.cluster.protocol.election.Election) Mockito.when(org.mockito.Mockito.when) DataSourceManager(org.neo4j.kernel.impl.transaction.state.DataSourceManager) Executors(java.util.concurrent.Executors) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Matchers.any(org.mockito.Matchers.any) CountDownLatch(java.util.concurrent.CountDownLatch) NullLogService(org.neo4j.kernel.impl.logging.NullLogService) ClusterMemberAvailability(org.neo4j.cluster.member.ClusterMemberAvailability) Mockito.inOrder(org.mockito.Mockito.inOrder) SimpleLogService(org.neo4j.kernel.impl.logging.SimpleLogService) ClusterClient(org.neo4j.cluster.client.ClusterClient) HighAvailabilityMemberChangeEvent(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberChangeEvent) Mockito.reset(org.mockito.Mockito.reset) Mockito.mock(org.mockito.Mockito.mock) ComException(org.neo4j.com.ComException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) InstanceId(org.neo4j.cluster.InstanceId) ClusterMemberAvailability(org.neo4j.cluster.member.ClusterMemberAvailability) CountDownLatch(java.util.concurrent.CountDownLatch) Election(org.neo4j.cluster.protocol.election.Election) URI(java.net.URI) Callable(java.util.concurrent.Callable) ScheduledFuture(java.util.concurrent.ScheduledFuture) ClusterClient(org.neo4j.cluster.client.ClusterClient) SwitchToSlaveCopyThenBranch(org.neo4j.kernel.ha.cluster.SwitchToSlaveCopyThenBranch) HighAvailabilityMemberChangeEvent(org.neo4j.kernel.ha.cluster.HighAvailabilityMemberChangeEvent) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) TimeUnit(java.util.concurrent.TimeUnit) LifeSupport(org.neo4j.kernel.lifecycle.LifeSupport) Supplier(java.util.function.Supplier) SwitchToMaster(org.neo4j.kernel.ha.cluster.SwitchToMaster) CancellationRequest(org.neo4j.helpers.CancellationRequest) Test(org.junit.Test)

Example 69 with Answer

use of org.mockito.stubbing.Answer in project netty by netty.

the class AbstractChannelTest method ensureSubsequentRegistrationDoesNotFireActive.

@Test
public void ensureSubsequentRegistrationDoesNotFireActive() throws Throwable {
    final EventLoop eventLoop = mock(EventLoop.class);
    // This allows us to have a single-threaded test
    when(eventLoop.inEventLoop()).thenReturn(true);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((Runnable) invocationOnMock.getArgument(0)).run();
            return null;
        }
    }).when(eventLoop).execute(any(Runnable.class));
    final TestChannel channel = new TestChannel();
    ChannelInboundHandler handler = mock(ChannelInboundHandler.class);
    channel.pipeline().addLast(handler);
    registerChannel(eventLoop, channel);
    channel.unsafe().deregister(new DefaultChannelPromise(channel));
    registerChannel(eventLoop, channel);
    verify(handler).handlerAdded(any(ChannelHandlerContext.class));
    // Should register twice
    verify(handler, times(2)).channelRegistered(any(ChannelHandlerContext.class));
    verify(handler).channelActive(any(ChannelHandlerContext.class));
    verify(handler).channelUnregistered(any(ChannelHandlerContext.class));
}
Also used : Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.Test)

Example 70 with Answer

use of org.mockito.stubbing.Answer in project neo4j by neo4j.

the class HeartbeatIAmAliveProcessorTest method shouldRevertToInverseUriLookupIfNoInstanceIdHeader.

/*
     * This test is required to ensure compatibility with the previous version. If we fail on non existing INSTANCE_ID
     * header then heartbeats may pause during rolling upgrades and cause timeouts, which we don't want.
     */
@Test
public void shouldRevertToInverseUriLookupIfNoInstanceIdHeader() throws Exception {
    final List<Message> sentOut = new LinkedList<Message>();
    String instance2UriString = "ha://2";
    // Given
    MessageHolder holder = mock(MessageHolder.class);
    // The sender, which adds messages outgoing to the list above.
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            sentOut.add((Message) invocation.getArguments()[0]);
            return null;
        }
    }).when(holder).offer(Matchers.<Message<MessageType>>any());
    ClusterContext mockContext = mock(ClusterContext.class);
    ClusterConfiguration mockConfiguration = mock(ClusterConfiguration.class);
    when(mockConfiguration.getIdForUri(URI.create(instance2UriString))).thenReturn(new InstanceId(2));
    when(mockConfiguration.getMembers()).thenReturn(new HashMap<InstanceId, URI>() {

        {
            put(new InstanceId(1), URI.create("ha://1"));
            put(new InstanceId(2), URI.create("ha://2"));
        }
    });
    when(mockContext.getConfiguration()).thenReturn(mockConfiguration);
    HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor(holder, mockContext);
    Message incoming = Message.to(mock(MessageType.class), URI.create("ha://someAwesomeInstanceInJapan")).setHeader(Message.FROM, instance2UriString);
    // WHEN
    processor.process(incoming);
    // THEN
    assertEquals(1, sentOut.size());
    assertEquals(HeartbeatMessage.i_am_alive, sentOut.get(0).getMessageType());
    assertEquals(new InstanceId(2), ((HeartbeatMessage.IAmAliveState) sentOut.get(0).getPayload()).getServer());
}
Also used : Message(org.neo4j.cluster.com.message.Message) InstanceId(org.neo4j.cluster.InstanceId) ClusterContext(org.neo4j.cluster.protocol.cluster.ClusterContext) ClusterConfiguration(org.neo4j.cluster.protocol.cluster.ClusterConfiguration) URI(java.net.URI) LinkedList(java.util.LinkedList) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) MessageHolder(org.neo4j.cluster.com.message.MessageHolder) InvocationOnMock(org.mockito.invocation.InvocationOnMock) MessageType(org.neo4j.cluster.com.message.MessageType) 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