Best Mockito code snippet using org.mockito.internal.util.Timer.duration
Source:MicrometerNodeMetricUpdaterTest.java
1/*2 * Copyright DataStax, Inc.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package com.datastax.oss.driver.internal.metrics.micrometer;17import static org.assertj.core.api.Assertions.assertThat;18import static org.mockito.Mockito.mock;19import static org.mockito.Mockito.spy;20import static org.mockito.Mockito.timeout;21import static org.mockito.Mockito.verify;22import static org.mockito.Mockito.when;23import ch.qos.logback.classic.Level;24import com.datastax.dse.driver.api.core.config.DseDriverOption;25import com.datastax.dse.driver.api.core.metrics.DseNodeMetric;26import com.datastax.oss.driver.api.core.config.DefaultDriverOption;27import com.datastax.oss.driver.api.core.config.DriverConfig;28import com.datastax.oss.driver.api.core.config.DriverExecutionProfile;29import com.datastax.oss.driver.api.core.config.DriverOption;30import com.datastax.oss.driver.api.core.metadata.Node;31import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric;32import com.datastax.oss.driver.api.core.metrics.NodeMetric;33import com.datastax.oss.driver.internal.core.context.InternalDriverContext;34import com.datastax.oss.driver.internal.core.metrics.AbstractMetricUpdater;35import com.datastax.oss.driver.internal.core.metrics.DefaultMetricId;36import com.datastax.oss.driver.internal.core.metrics.MetricId;37import com.datastax.oss.driver.internal.core.metrics.MetricIdGenerator;38import com.datastax.oss.driver.internal.core.util.LoggerTest;39import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap;40import com.tngtech.java.junit.dataprovider.DataProvider;41import com.tngtech.java.junit.dataprovider.DataProviderRunner;42import com.tngtech.java.junit.dataprovider.UseDataProvider;43import io.micrometer.core.instrument.Timer;44import io.micrometer.core.instrument.distribution.HistogramSnapshot;45import io.micrometer.core.instrument.simple.SimpleMeterRegistry;46import java.time.Duration;47import java.util.Arrays;48import java.util.Collections;49import java.util.Set;50import java.util.concurrent.TimeUnit;51import org.junit.Test;52import org.junit.runner.RunWith;53@RunWith(DataProviderRunner.class)54public class MicrometerNodeMetricUpdaterTest {55 private static final MetricId METRIC_ID = new DefaultMetricId("irrelevant", ImmutableMap.of());56 @Test57 public void should_log_warning_when_provided_eviction_time_setting_is_too_low() {58 // given59 LoggerTest.LoggerSetup logger =60 LoggerTest.setupTestLogger(AbstractMetricUpdater.class, Level.WARN);61 Node node = mock(Node.class);62 InternalDriverContext context = mock(InternalDriverContext.class);63 DriverExecutionProfile profile = mock(DriverExecutionProfile.class);64 DriverConfig config = mock(DriverConfig.class);65 MetricIdGenerator generator = mock(MetricIdGenerator.class);66 Set<NodeMetric> enabledMetrics = Collections.singleton(DefaultNodeMetric.CQL_MESSAGES);67 Duration expireAfter = AbstractMetricUpdater.MIN_EXPIRE_AFTER.minusMinutes(1);68 // when69 when(context.getSessionName()).thenReturn("prefix");70 when(context.getConfig()).thenReturn(config);71 when(config.getDefaultProfile()).thenReturn(profile);72 when(context.getMetricIdGenerator()).thenReturn(generator);73 when(profile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER))74 .thenReturn(expireAfter);75 when(generator.nodeMetricId(node, DefaultNodeMetric.CQL_MESSAGES)).thenReturn(METRIC_ID);76 when(profile.getDuration(DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_HIGHEST))77 .thenReturn(Duration.ofSeconds(10));78 when(profile.getDuration(DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_LOWEST))79 .thenReturn(Duration.ofMillis(1));80 when(profile.getInt(DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_DIGITS)).thenReturn(5);81 MicrometerNodeMetricUpdater updater =82 new MicrometerNodeMetricUpdater(node, context, enabledMetrics, new SimpleMeterRegistry());83 // then84 assertThat(updater.getExpireAfter()).isEqualTo(AbstractMetricUpdater.MIN_EXPIRE_AFTER);85 verify(logger.appender, timeout(500).times(1)).doAppend(logger.loggingEventCaptor.capture());86 assertThat(logger.loggingEventCaptor.getValue().getMessage()).isNotNull();87 assertThat(logger.loggingEventCaptor.getValue().getFormattedMessage())88 .contains(89 String.format(90 "[prefix] Value too low for %s: %s. Forcing to %s instead.",91 DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER.getPath(),92 expireAfter,93 AbstractMetricUpdater.MIN_EXPIRE_AFTER));94 }95 @Test96 @UseDataProvider(value = "acceptableEvictionTimes")97 public void should_not_log_warning_when_provided_eviction_time_setting_is_acceptable(98 Duration expireAfter) {99 // given100 LoggerTest.LoggerSetup logger =101 LoggerTest.setupTestLogger(AbstractMetricUpdater.class, Level.WARN);102 Node node = mock(Node.class);103 InternalDriverContext context = mock(InternalDriverContext.class);104 DriverExecutionProfile profile = mock(DriverExecutionProfile.class);105 DriverConfig config = mock(DriverConfig.class);106 MetricIdGenerator generator = mock(MetricIdGenerator.class);107 Set<NodeMetric> enabledMetrics = Collections.singleton(DefaultNodeMetric.CQL_MESSAGES);108 // when109 when(context.getSessionName()).thenReturn("prefix");110 when(context.getConfig()).thenReturn(config);111 when(config.getDefaultProfile()).thenReturn(profile);112 when(context.getMetricIdGenerator()).thenReturn(generator);113 when(profile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER))114 .thenReturn(expireAfter);115 when(generator.nodeMetricId(node, DefaultNodeMetric.CQL_MESSAGES)).thenReturn(METRIC_ID);116 when(profile.getDuration(DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_HIGHEST))117 .thenReturn(Duration.ofSeconds(10));118 when(profile.getDuration(DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_LOWEST))119 .thenReturn(Duration.ofMillis(1));120 when(profile.getInt(DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_DIGITS)).thenReturn(5);121 MicrometerNodeMetricUpdater updater =122 new MicrometerNodeMetricUpdater(node, context, enabledMetrics, new SimpleMeterRegistry());123 // then124 assertThat(updater.getExpireAfter()).isEqualTo(expireAfter);125 verify(logger.appender, timeout(500).times(0)).doAppend(logger.loggingEventCaptor.capture());126 }127 @DataProvider128 public static Object[][] acceptableEvictionTimes() {129 return new Object[][] {130 {AbstractMetricUpdater.MIN_EXPIRE_AFTER},131 {AbstractMetricUpdater.MIN_EXPIRE_AFTER.plusMinutes(1)}132 };133 }134 @Test135 @UseDataProvider(value = "timerMetrics")136 public void should_create_timer(137 NodeMetric metric,138 DriverOption lowest,139 DriverOption highest,140 DriverOption digits,141 DriverOption sla) {142 // given143 Node node = mock(Node.class);144 InternalDriverContext context = mock(InternalDriverContext.class);145 DriverExecutionProfile profile = mock(DriverExecutionProfile.class);146 DriverConfig config = mock(DriverConfig.class);147 MetricIdGenerator generator = mock(MetricIdGenerator.class);148 Set<NodeMetric> enabledMetrics = Collections.singleton(metric);149 // when150 when(context.getSessionName()).thenReturn("prefix");151 when(context.getConfig()).thenReturn(config);152 when(config.getDefaultProfile()).thenReturn(profile);153 when(context.getMetricIdGenerator()).thenReturn(generator);154 when(profile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER))155 .thenReturn(Duration.ofHours(1));156 when(profile.getDuration(lowest)).thenReturn(Duration.ofMillis(10));157 when(profile.getDuration(highest)).thenReturn(Duration.ofSeconds(1));158 when(profile.getInt(digits)).thenReturn(5);159 when(profile.isDefined(sla)).thenReturn(true);160 when(profile.getDurationList(sla))161 .thenReturn(Arrays.asList(Duration.ofMillis(100), Duration.ofMillis(500)));162 when(generator.nodeMetricId(node, metric)).thenReturn(METRIC_ID);163 SimpleMeterRegistry registry = spy(new SimpleMeterRegistry());164 MicrometerNodeMetricUpdater updater =165 new MicrometerNodeMetricUpdater(node, context, enabledMetrics, registry);166 for (int i = 0; i < 10; i++) {167 updater.updateTimer(metric, null, 100, TimeUnit.MILLISECONDS);168 }169 // then170 Timer timer = registry.find(METRIC_ID.getName()).timer();171 assertThat(timer).isNotNull();172 assertThat(timer.count()).isEqualTo(10);173 HistogramSnapshot snapshot = timer.takeSnapshot();174 assertThat(snapshot.histogramCounts()).hasSize(2);175 }176 @DataProvider177 public static Object[][] timerMetrics() {178 return new Object[][] {179 {180 DefaultNodeMetric.CQL_MESSAGES,181 DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_LOWEST,182 DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_HIGHEST,183 DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_DIGITS,184 DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_SLO,185 },186 {187 DseNodeMetric.GRAPH_MESSAGES,188 DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_LOWEST,189 DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_HIGHEST,190 DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_DIGITS,191 DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_SLO,192 },193 };194 }195}...
Source:VerificationOverTimeImpl.java
...13 * once it does, or waits until it is definitely satisfied once the full time has passed.14 */15public class VerificationOverTimeImpl implements VerificationMode {16 private final long pollingPeriodMillis;17 private final long durationMillis;18 private final VerificationMode delegate;19 private final boolean returnOnSuccess;20 private final Timer timer;21 /**22 * Create this verification mode, to be used to verify invocation ongoing data later.23 *24 * @param pollingPeriodMillis The frequency to poll delegate.verify(), to check whether the delegate has been satisfied25 * @param durationMillis The max time to wait (in millis) for the delegate verification mode to be satisfied26 * @param delegate The verification mode to delegate overall success or failure to27 * @param returnOnSuccess Whether to immediately return successfully once the delegate is satisfied (as in28 * {@link org.mockito.verification.VerificationWithTimeout}, or to only return once29 * the delegate is satisfied and the full duration has passed (as in30 * {@link org.mockito.verification.VerificationAfterDelay}).31 */32 public VerificationOverTimeImpl(long pollingPeriodMillis, long durationMillis, VerificationMode delegate, boolean returnOnSuccess) {33 this(pollingPeriodMillis, durationMillis, delegate, returnOnSuccess, new Timer(durationMillis));34 }35 /**36 * Create this verification mode, to be used to verify invocation ongoing data later.37 *38 * @param pollingPeriodMillis The frequency to poll delegate.verify(), to check whether the delegate has been satisfied39 * @param durationMillis The max time to wait (in millis) for the delegate verification mode to be satisfied40 * @param delegate The verification mode to delegate overall success or failure to41 * @param returnOnSuccess Whether to immediately return successfully once the delegate is satisfied (as in42 * {@link org.mockito.verification.VerificationWithTimeout}, or to only return once43 * the delegate is satisfied and the full duration has passed (as in44 * {@link org.mockito.verification.VerificationAfterDelay}).45 * @param timer Checker of whether the duration of the verification is still acceptable46 */47 public VerificationOverTimeImpl(long pollingPeriodMillis, long durationMillis, VerificationMode delegate, boolean returnOnSuccess, Timer timer) {48 this.pollingPeriodMillis = pollingPeriodMillis;49 this.durationMillis = durationMillis;50 this.delegate = delegate;51 this.returnOnSuccess = returnOnSuccess;52 this.timer = timer;53 }54 /**55 * Verify the given ongoing verification data, and confirm that it satisfies the delegate verification mode56 * before the full duration has passed.57 *58 * In practice, this polls the delegate verification mode until it is satisfied. If it is not satisfied once59 * the full duration has passed, the last error returned by the delegate verification mode will be thrown60 * here in turn. This may be thrown early if the delegate is unsatisfied and the verification mode is known61 * to never recover from this situation (e.g. {@link AtMost}).62 *63 * If it is satisfied before the full duration has passed, behaviour is dependent on the returnOnSuccess parameter64 * given in the constructor. If true, this verification mode is immediately satisfied once the delegate is. If65 * false, this verification mode is not satisfied until the delegate is satisfied and the full time has passed.66 *67 * @throws MockitoAssertionError if the delegate verification mode does not succeed before the timeout68 */69 public void verify(VerificationData data) {70 AssertionError error = null;71 timer.start();72 while (timer.isCounting()) {73 try {74 delegate.verify(data);75 if (returnOnSuccess) {76 return;77 } else {78 error = null;79 }80 } catch (MockitoAssertionError e) {81 error = handleVerifyException(e);82 }83 catch (AssertionError e) {84 error = handleVerifyException(e);85 }86 }87 if (error != null) {88 throw error;89 }90 }91 private AssertionError handleVerifyException(AssertionError e) {92 if (canRecoverFromFailure(delegate)) {93 sleep(pollingPeriodMillis);94 return e;95 } else {96 throw e;97 }98 }99 protected boolean canRecoverFromFailure(VerificationMode verificationMode) {100 return !(verificationMode instanceof AtMost || verificationMode instanceof NoMoreInteractions);101 }102 private void sleep(long sleep) {103 try {104 Thread.sleep(sleep);105 } catch (InterruptedException ie) {106 // oups. not much luck.107 }108 }109 public long getPollingPeriod() {110 return pollingPeriodMillis;111 }112 public long getDuration() {113 return durationMillis;114 }115 public VerificationMode getDelegate() {116 return delegate;117 }118}...
Source:MicrometerSessionMetricUpdaterTest.java
1/*2 * Copyright DataStax, Inc.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package com.datastax.oss.driver.internal.metrics.micrometer;17import static org.assertj.core.api.Assertions.assertThat;18import static org.mockito.Mockito.mock;19import static org.mockito.Mockito.spy;20import static org.mockito.Mockito.when;21import com.datastax.dse.driver.api.core.config.DseDriverOption;22import com.datastax.dse.driver.api.core.metrics.DseSessionMetric;23import com.datastax.oss.driver.api.core.config.DefaultDriverOption;24import com.datastax.oss.driver.api.core.config.DriverConfig;25import com.datastax.oss.driver.api.core.config.DriverExecutionProfile;26import com.datastax.oss.driver.api.core.config.DriverOption;27import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric;28import com.datastax.oss.driver.api.core.metrics.SessionMetric;29import com.datastax.oss.driver.internal.core.context.InternalDriverContext;30import com.datastax.oss.driver.internal.core.metrics.DefaultMetricId;31import com.datastax.oss.driver.internal.core.metrics.MetricId;32import com.datastax.oss.driver.internal.core.metrics.MetricIdGenerator;33import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap;34import com.tngtech.java.junit.dataprovider.DataProvider;35import com.tngtech.java.junit.dataprovider.DataProviderRunner;36import com.tngtech.java.junit.dataprovider.UseDataProvider;37import io.micrometer.core.instrument.Timer;38import io.micrometer.core.instrument.distribution.HistogramSnapshot;39import io.micrometer.core.instrument.simple.SimpleMeterRegistry;40import java.time.Duration;41import java.util.Arrays;42import java.util.Collections;43import java.util.Set;44import java.util.concurrent.TimeUnit;45import org.junit.Test;46import org.junit.runner.RunWith;47@RunWith(DataProviderRunner.class)48public class MicrometerSessionMetricUpdaterTest {49 private static final MetricId METRIC_ID = new DefaultMetricId("irrelevant", ImmutableMap.of());50 @Test51 @UseDataProvider(value = "timerMetrics")52 public void should_create_timer(53 SessionMetric metric,54 DriverOption lowest,55 DriverOption highest,56 DriverOption digits,57 DriverOption sla) {58 // given59 InternalDriverContext context = mock(InternalDriverContext.class);60 DriverExecutionProfile profile = mock(DriverExecutionProfile.class);61 DriverConfig config = mock(DriverConfig.class);62 MetricIdGenerator generator = mock(MetricIdGenerator.class);63 Set<SessionMetric> enabledMetrics = Collections.singleton(metric);64 // when65 when(context.getSessionName()).thenReturn("prefix");66 when(context.getConfig()).thenReturn(config);67 when(config.getDefaultProfile()).thenReturn(profile);68 when(context.getMetricIdGenerator()).thenReturn(generator);69 when(profile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER))70 .thenReturn(Duration.ofHours(1));71 when(profile.getDuration(lowest)).thenReturn(Duration.ofMillis(10));72 when(profile.getDuration(highest)).thenReturn(Duration.ofSeconds(1));73 when(profile.getInt(digits)).thenReturn(5);74 when(profile.isDefined(sla)).thenReturn(true);75 when(profile.getDurationList(sla))76 .thenReturn(Arrays.asList(Duration.ofMillis(100), Duration.ofMillis(500)));77 when(generator.sessionMetricId(metric)).thenReturn(METRIC_ID);78 SimpleMeterRegistry registry = spy(new SimpleMeterRegistry());79 MicrometerSessionMetricUpdater updater =80 new MicrometerSessionMetricUpdater(context, enabledMetrics, registry);81 for (int i = 0; i < 10; i++) {82 updater.updateTimer(metric, null, 100, TimeUnit.MILLISECONDS);83 }84 // then85 Timer timer = registry.find(METRIC_ID.getName()).timer();86 assertThat(timer).isNotNull();87 assertThat(timer.count()).isEqualTo(10);88 HistogramSnapshot snapshot = timer.takeSnapshot();89 assertThat(snapshot.histogramCounts()).hasSize(2);90 }91 @DataProvider92 public static Object[][] timerMetrics() {93 return new Object[][] {94 {95 DefaultSessionMetric.CQL_REQUESTS,96 DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_LOWEST,97 DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_HIGHEST,98 DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_DIGITS,99 DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_SLO,100 },101 {102 DseSessionMetric.GRAPH_REQUESTS,103 DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_LOWEST,104 DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_HIGHEST,105 DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_DIGITS,106 DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_SLO,107 },108 {109 DseSessionMetric.CONTINUOUS_CQL_REQUESTS,110 DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_LOWEST,111 DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_HIGHEST,112 DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_DIGITS,113 DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_SLO,114 },115 {116 DefaultSessionMetric.THROTTLING_DELAY,117 DefaultDriverOption.METRICS_SESSION_THROTTLING_LOWEST,118 DefaultDriverOption.METRICS_SESSION_THROTTLING_HIGHEST,119 DefaultDriverOption.METRICS_SESSION_THROTTLING_DIGITS,120 DefaultDriverOption.METRICS_SESSION_THROTTLING_SLO,121 },122 };123 }124}...
Source:ReplayAwareScopeTest.java
1/*2 * Copyright (C) 2020 Temporal Technologies, Inc. All Rights Reserved.3 *4 * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.5 *6 * Modifications copyright (C) 2017 Uber Technologies, Inc.7 *8 * Licensed under the Apache License, Version 2.0 (the "License"). You may not9 * use this file except in compliance with the License. A copy of the License is10 * located at11 *12 * http://aws.amazon.com/apache2.013 *14 * or in the "license" file accompanying this file. This file is distributed on15 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either16 * express or implied. See the License for the specific language governing17 * permissions and limitations under the License.18 */19package io.temporal.metrics;20import static org.mockito.Mockito.mock;21import static org.mockito.Mockito.never;22import static org.mockito.Mockito.times;23import static org.mockito.Mockito.verify;24import static org.mockito.Mockito.when;25import com.uber.m3.tally.Counter;26import com.uber.m3.tally.Gauge;27import com.uber.m3.tally.Histogram;28import com.uber.m3.tally.Scope;29import com.uber.m3.tally.Stopwatch;30import com.uber.m3.tally.Timer;31import com.uber.m3.tally.ValueBuckets;32import com.uber.m3.util.Duration;33import io.temporal.internal.metrics.ReplayAwareScope;34import io.temporal.internal.replay.ReplayAware;35import java.util.function.Supplier;36import org.junit.Test;37public class ReplayAwareScopeTest {38 private static class TestContext implements ReplayAware {39 boolean isReplaying;40 public TestContext(boolean isReplaying) {41 this.isReplaying = isReplaying;42 }43 @Override44 public boolean isReplaying() {45 return isReplaying;46 }47 }48 @Test49 public void testReplayAwareScopeReplaying() {50 Scope scope = mock(Scope.class);51 Counter counter = mock(Counter.class);52 Gauge gauge = mock(Gauge.class);53 Timer timer = mock(Timer.class);54 Histogram histogram = mock(Histogram.class);55 @SuppressWarnings("deprecation")56 com.uber.m3.tally.Buckets buckets = ValueBuckets.linear(0, 10, 10);57 when(scope.counter("test-counter")).thenReturn(counter);58 when(scope.gauge("test-gauge")).thenReturn(gauge);59 when(scope.timer("test-timer")).thenReturn(timer);60 when(scope.histogram("test-histogram", buckets)).thenReturn(histogram);61 TestContext context = new TestContext(true);62 Scope replayAwareScope = new ReplayAwareScope(scope, context, System::currentTimeMillis);63 replayAwareScope.counter("test-counter").inc(1);64 replayAwareScope.gauge("test-gauge").update(100.0);65 replayAwareScope.timer("test-timer").record(Duration.ofMillis(100));66 replayAwareScope.histogram("test-histogram", buckets).recordValue(10);67 replayAwareScope.histogram("test-histogram", buckets).recordDuration(Duration.ofHours(1));68 verify(counter, never()).inc(1);69 verify(gauge, never()).update(100.0);70 verify(timer, never()).record(Duration.ofMillis(100));71 verify(histogram, never()).recordValue(10);72 verify(histogram, never()).recordDuration(Duration.ofHours(1));73 }74 @Test75 public void testReplayAwareScopeNotReplaying() {76 Scope scope = mock(Scope.class);77 Counter counter = mock(Counter.class);78 Gauge gauge = mock(Gauge.class);79 Timer timer = mock(Timer.class);80 Histogram histogram = mock(Histogram.class);81 @SuppressWarnings("deprecation")82 com.uber.m3.tally.Buckets buckets = ValueBuckets.linear(0, 10, 10);83 when(scope.counter("test-counter")).thenReturn(counter);84 when(scope.gauge("test-gauge")).thenReturn(gauge);85 when(scope.timer("test-timer")).thenReturn(timer);86 when(scope.histogram("test-histogram", buckets)).thenReturn(histogram);87 TestContext context = new TestContext(false);88 Scope replayAwareScope = new ReplayAwareScope(scope, context, System::currentTimeMillis);89 replayAwareScope.counter("test-counter").inc(1);90 replayAwareScope.gauge("test-gauge").update(100.0);91 replayAwareScope.timer("test-timer").record(Duration.ofMillis(100));92 replayAwareScope.histogram("test-histogram", buckets).recordValue(10);93 replayAwareScope.histogram("test-histogram", buckets).recordDuration(Duration.ofHours(1));94 verify(counter, times(1)).inc(1);95 verify(gauge, times(1)).update(100.0);96 verify(timer, times(1)).record(Duration.ofMillis(100));97 verify(histogram, times(1)).recordValue(10);98 verify(histogram, times(1)).recordDuration(Duration.ofHours(1));99 }100 static class TestClock implements Supplier<Long> {101 private long currTime;102 @Override103 public Long get() {104 return currTime;105 }106 void setTime(long currTime) {107 this.currTime = currTime;108 }109 }110 @Test111 public void testCustomClockForTimer() {112 Scope scope = mock(Scope.class);113 Timer timer = mock(Timer.class);114 Histogram histogram = mock(Histogram.class);115 @SuppressWarnings("deprecation")116 com.uber.m3.tally.Buckets buckets = ValueBuckets.linear(0, 10, 10);117 when(scope.timer("test-timer")).thenReturn(timer);118 when(scope.histogram("test-histogram", buckets)).thenReturn(histogram);119 TestContext context = new TestContext(false);120 TestClock clock = new TestClock();121 clock.setTime(0);122 Scope replayAwareScope = new ReplayAwareScope(scope, context, clock);123 Stopwatch sw = replayAwareScope.timer("test-timer").start();124 clock.setTime(100);125 sw.stop();126 sw = replayAwareScope.histogram("test-histogram", buckets).start();127 clock.setTime(150);128 sw.stop();129 verify(timer, times(1)).record(Duration.ofMillis(100));130 verify(histogram, times(1)).recordDuration(Duration.ofMillis(50));131 }132}...
Source:TimerTest.java
...15 public ExpectedException expectedException = ExpectedException.none();16 @Test17 public void should_return_true_if_task_is_in_acceptable_time_bounds() {18 //given19 long duration = 10000L;20 Timer timer = new Timer(duration);21 //when22 timer.start();23 //then24 Assertions.assertThat(timer.isCounting()).isTrue();25 }26 @Test27 public void should_return_false_when_time_run_out() throws Exception {28 //given29 Timer timer = new Timer(0);30 timer.start();31 //when32 oneMillisecondPasses();33 //then34 Assertions.assertThat(timer.isCounting()).isFalse();35 }36 @Test37 public void should_throw_friendly_reminder_exception_when_duration_is_negative() {38 expectedException.expect(FriendlyReminderException.class);39 expectedException.expectMessage("Don't panic! I'm just a friendly reminder!");40 new Timer(-1);41 }42 private void oneMillisecondPasses() throws InterruptedException {43 Thread.sleep(1);44 }45}...
Source:Timer.java
...4 */5package org.mockito.internal.util;6import static org.mockito.internal.exceptions.Reporter.cannotCreateTimerWithNegativeDurationTime;7public class Timer {8 private final long durationMillis;9 private long startTime = -1;10 public Timer(long durationMillis) {11 validateInput(durationMillis);12 this.durationMillis = durationMillis;13 }14 /**15 * Informs whether the timer is still counting down.16 */17 public boolean isCounting() {18 assert startTime != -1;19 return System.currentTimeMillis() - startTime <= durationMillis;20 }21 /**22 * Starts the timer count down.23 */24 public void start() {25 startTime = System.currentTimeMillis();26 }27 private void validateInput(long durationMillis) {28 if (durationMillis < 0) {29 throw cannotCreateTimerWithNegativeDurationTime(durationMillis);30 }31 }32 public long duration() {33 return durationMillis;34 }35}...
duration
Using AI Code Generation
1import org.mockito.internal.util.Timer;2public class Test {3 public static void main(String[] args) {4 Timer timer = new Timer();5 timer.start();6 timer.stop();7 System.out.println(timer.duration());8 }9}10import org.mockito.internal.util.Timer;11public class Test {12 public static void main(String[] args) {13 Timer timer = new Timer();14 timer.start();15 timer.stop();16 System.out.println(timer.duration());17 }18}19import org.mockito.internal.util.Timer;20public class Test {21 public static void main(String[] args) {22 Timer timer = new Timer();23 timer.start();24 timer.stop();25 System.out.println(timer.duration());26 }27}28import org.mockito.internal.util.Timer;29public class Test {30 public static void main(String[] args) {31 Timer timer = new Timer();32 timer.start();33 timer.stop();34 System.out.println(timer.duration());35 }36}37import org.mockito.internal.util.Timer;38public class Test {39 public static void main(String[] args) {40 Timer timer = new Timer();41 timer.start();42 timer.stop();43 System.out.println(timer.duration());44 }45}46import org.mockito.internal.util.Timer;47public class Test {48 public static void main(String[] args) {49 Timer timer = new Timer();50 timer.start();51 timer.stop();52 System.out.println(timer.duration());53 }54}55import org.mockito.internal.util.Timer;56public class Test {57 public static void main(String[] args) {58 Timer timer = new Timer();59 timer.start();60 timer.stop();61 System.out.println(timer.duration());
duration
Using AI Code Generation
1package org.mockito.internal.util;2import org.junit.Test;3import org.mockito.internal.util.Timer;4import static org.junit.Assert.*;5public class TimerTest {6 public void testDuration() {7 Timer timer = new Timer();8 long duration = timer.duration();9 assertTrue(duration > 0);10 }11}12at java.lang.ClassLoader.defineClass1(Native Method)13at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)14at java.lang.ClassLoader.defineClass(ClassLoader.java:615)15at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)16at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)17at java.net.URLClassLoader.access$000(URLClassLoader.java:58)18at java.net.URLClassLoader$1.run(URLClassLoader.java:197)19at java.security.AccessController.doPrivileged(Native Method)20at java.net.URLClassLoader.findClass(URLClassLoader.java:190)21at java.lang.ClassLoader.loadClass(ClassLoader.java:306)22at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)23at java.lang.ClassLoader.loadClass(ClassLoader.java:247)24at java.net.URLClassLoader$1.run(URLClassLoader.java:202)25at java.security.AccessController.doPrivileged(Native Method)26at java.net.URLClassLoader.findClass(URLClassLoader.java:190)27at java.lang.ClassLoader.loadClass(ClassLoader.java:306)28at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)29at java.lang.ClassLoader.loadClass(ClassLoader.java:247)30Related posts: How to use Mockito matchers to test the arguments in the method call? Mockito: How to mock a method that returns a generic type? Mockito: How to use the verify() method to verify the number of times a method is called? Mockito: How to use the verify() method to verify
duration
Using AI Code Generation
1import org.mockito.internal.util.Timer;2import org.mockito.internal.util.Timer;3public class 1 {4 public static void main(String[] args) {5 Timer timer = new Timer();6 timer.start();7 timer.stop();8 System.out.println(timer.duration());9 }10}
duration
Using AI Code Generation
1import org.mockito.internal.util.Timer;2import org.mockito.internal.util.Timer;3public class 1 {4 public static void main(String[] args) {5 Timer timer = new Timer();6 timer.start();7 System.out.println("Some code");8 timer.stop();9 long duration = timer.duration();10 System.out.println("Duration: " + duration);11 }12}
duration
Using AI Code Generation
1import org.mockito.internal.util.Timer;2import java.util.concurrent.TimeUnit;3class Test{4 public static void main(String[] args){5 Timer timer = new Timer();6 timer.start();7 timer.stop();8 long time = timer.duration(TimeUnit.MILLISECONDS);9 System.out.println("Time taken is "+time+" milliseconds");10 }11}12Recommended Posts: Java.util.Timer Java 8 | Set 2 (Methods and Examples)13Java.util.Timer Java 8 | Set 1 (Introduction)14Java.util.Timer Java 8 | Set 3 (Scheduling Tasks)15Java.util.Timer Java 8 | Set 4 (Canceling Tasks)16Java.util.Timer Java 8 | Set 5 (TimerTask Class)17Java.util.Timer Java 8 | Set 6 (TimerTask Methods)18Java.util.Timer Java 8 | Set 7 (TimerTask Example)19Java.util.Timer Java 8 | Set 8 (TimerTask Example)20Java.util.Timer Java 8 | Set 9 (TimerTask Example)21Java.util.Timer Java 8 | Set 10 (TimerTask Example)22Java.util.Timer Java 8 | Set 11 (TimerTask Example)23Java.util.Timer Java 8 | Set 12 (TimerTask Example)24Java.util.Timer Java 8 | Set 13 (TimerTask Example)25Java.util.Timer Java 8 | Set 14 (TimerTask Example)26Java.util.Timer Java 8 | Set 15 (TimerTask Example)27Java.util.Timer Java 8 | Set 16 (TimerTask Example)28Java.util.Timer Java 8 | Set 17 (TimerTask Example)29Java.util.Timer Java 8 | Set 18 (TimerTask Example)30Java.util.Timer Java 8 | Set 19 (TimerTask Example)31Java.util.Timer Java 8 | Set 20 (TimerTask Example)
duration
Using AI Code Generation
1import org.mockito.internal.util.Timer;2import java.util.concurrent.TimeUnit;3public class 1 {4 public static void main(String[] args) {5 Timer timer = new Timer();6 timer.start();7 System.out.println("Hello World");8 timer.stop();9 System.out.println("Time taken to execute the method: " + timer.duration(TimeUnit.MILLISECONDS) + " milliseconds");10 }11}12Duration.between() in Java with Examples13Duration.of() in Java with Examples14Duration.ofDays() in Java with Examples15Duration.ofHours() in Java with Examples16Duration.ofMillis() in Java with Examples17Duration.ofMinutes() in Java with Examples18Duration.ofNanos() in Java with Examples19Duration.ofSeconds() in Java with Examples20Duration.parse() in Java with Examples21Duration.plus() in Java with Examples22Duration.plusDays() in Java with Examples23Duration.plusHours() in Java with Examples24Duration.plusMillis() in Java with Examples25Duration.plusMinutes() in Java with Examples26Duration.plusNanos() in Java with Examples27Duration.plusSeconds() in Java with Examples28Duration.toDays() in Java with Examples29Duration.toHours() in Java with Examples30Duration.toMillis() in Java with Examples
duration
Using AI Code Generation
1package org.mockito.internal.util;2import org.junit.Test;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.verify;5import static org.mockito.Mockito.times;6import static org.mockito.Mockito.withSettings;7import static org.mockito.Mockito.after;8import static org.mockito.Mockito.timeout;9import static org.mockito.Mockito.only;10import static org.mockito.Mockito.never;11import static org.mockito.Mockito.inOrder;12import static org.mockito.Mockito.doThrow;13import static org.mockito.Mockito.doReturn;14import static org.mockito.Mockito.doNothing;15import static org.mockito.Mockito.doAnswer;16import static org.mockito.Mockito.spy;17import static org.mockito.Mockito.verifyNoMoreInteractions;18import static org.mockito.Mockito.verifyZeroInteractions;19import static org.mockito.Mockito.verifyNoInteractions;20import static org.mockito.Mockito.when;21import static org.mockito.Mockito.any;22import static org.mockito.Mockito.anyString;23import static org.mockito.Mockito.anyInt;24import static org.mockito.Mockito.anyLong;25import static org.mockito.Mockito.anyBoolean;26import static org.mockito.Mockito.anyByte;27import static org.mockito.Mockito.anyShort;28import static org.mockito.Mockito.anyChar;29import static org.mockito.Mockito.anyFloat;30import static org.mockito.Mockito.anyDouble;31import static org.mockito.Mockito.anyVararg;32import static org.mockito.Mockito.eq;33import static org.mockito.Mockito.same;34import static org.mockito.Mockito.contains;35import static org.mockito.Mockito.argThat;36import static org.mockito.Mockito.notNull;37import static org.mockito.Mockito.isNull;38import static org.mockito.Mockito.isNotNull;39import static org.mockito.Mockito.isA;40import static org
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!