下面列出了怎么用org.mockito.internal.verification.Times的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@SuppressWarnings("unchecked")
public void inUseChannelsAreFlaggedToBeClosed() throws Exception {
// Given
MockChannel channel = new MockChannel();
channel.attr(ChannelAttributeKey.IN_USE).set(true);
ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
Mockito.when(ctx.channel()).thenReturn(channel);
// When
new OldConnectionReaperHandler(1).handlerAdded(ctx);
channel.runAllPendingTasks();
// Then
Mockito.verify(ctx, new Times(0)).close();
Mockito.verify(ctx, new Times(0)).close(any());
assertThat(channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).get()).isTrue();
}
@Test
public void notInUseChannelsAreClosed() throws Exception {
// Given
MockChannel channel = new MockChannel();
channel.attr(ChannelAttributeKey.IN_USE).set(false);
ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
Mockito.when(ctx.channel()).thenReturn(channel);
// When
new OldConnectionReaperHandler(1).handlerAdded(ctx);
channel.runAllPendingTasks();
// Then
Mockito.verify(ctx, new Times(1)).close();
Mockito.verify(ctx, new Times(0)).close(any());
}
@Test
public void idleConnectionReaperDoesNotReapActiveConnections() throws InterruptedException {
Duration maxIdleTime = Duration.ofSeconds(2);
try(SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.connectionMaxIdleTime(maxIdleTime)
.buildWithDefaults(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)) {
Instant end = Instant.now().plus(maxIdleTime.plusSeconds(1));
// Send requests for longer than the max-idle time, ensuring no connections are closed.
while (Instant.now().isBefore(end)) {
makeRequest(client);
Thread.sleep(100);
verify(TRAFFIC_LISTENER, new Times(0)).closed(any());
}
// Do nothing for longer than the max-idle time, ensuring connections are closed.
Thread.sleep(maxIdleTime.plusSeconds(1).toMillis());
verify(TRAFFIC_LISTENER, new AtLeast(1)).closed(any());
}
}
@Test
public void oldConnectionReaperReapsActiveConnections() throws InterruptedException {
Duration connectionTtl = Duration.ofMillis(200);
try (SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder()
.connectionTimeToLive(connectionTtl)
.buildWithDefaults(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)) {
Instant end = Instant.now().plus(Duration.ofSeconds(5));
verify(TRAFFIC_LISTENER, new Times(0)).closed(any());
// Send requests frequently, validating that connections are still being closed.
while (Instant.now().isBefore(end)) {
makeRequest(client);
Thread.sleep(100);
}
verify(TRAFFIC_LISTENER, new AtLeast(20)).closed(any());
}
}
@Test
public void testCreateGroupedJvmsTemplate() {
final InputStream metaDataIn = this.getClass().getClassLoader()
.getResourceAsStream("resource-service-test-files/create-grouped-jvms-template-test-metadata.json");
final InputStream templateIn = this.getClass().getClassLoader()
.getResourceAsStream("resource-service-test-files/server.xml.tpl");
final Set<Jvm> jvmSet = new HashSet<>();
jvmSet.add(mock(Jvm.class));
jvmSet.add(mock(Jvm.class));
final Group mockGroup = mock(Group.class);
when(mockGroup.getJvms()).thenReturn(jvmSet);
when(Config.mockGroupPesistenceService.getGroup(eq("HEALTH CHECK 4.0"))).thenReturn(mockGroup);
User mockUser = mock(User.class);
when(mockUser.getId()).thenReturn("user-id");
resourceService.createTemplate(metaDataIn, templateIn, "test-app-name", mockUser);
verify(Config.mockJvmPersistenceService, new Times(2)).uploadJvmConfigTemplate(any(UploadJvmConfigTemplateRequest.class));
verify(Config.mockGroupPesistenceService).populateGroupJvmTemplates(eq("HEALTH CHECK 4.0"), any(List.class));
}
@Test
public void testCreateGroupedWebServersTemplate() {
final InputStream metaDataIn = this.getClass().getClassLoader()
.getResourceAsStream("resource-service-test-files/create-grouped-ws-template-test-metadata.json");
final InputStream templateIn = this.getClass().getClassLoader()
.getResourceAsStream("resource-service-test-files/httpd.conf.tpl");
final Set<WebServer> webServerSet = new HashSet<>();
webServerSet.add(mock(WebServer.class));
webServerSet.add(mock(WebServer.class));
final Group mockGroup = mock(Group.class);
when(mockGroup.getWebServers()).thenReturn(webServerSet);
when(mockGroup.getName()).thenReturn("HEALTH CHECK 4.0");
when(Config.mockGroupPesistenceService.getGroupWithWebServers(eq("HEALTH CHECK 4.0"))).thenReturn(mockGroup);
User mockUser = mock(User.class);
when(mockUser.getId()).thenReturn("user-id");
resourceService.createTemplate(metaDataIn, templateIn, "test-app-name", mockUser);
verify(Config.mockWebServerPersistenceService, new Times(2)).uploadWebServerConfigTemplate(any(UploadWebServerTemplateRequest.class), eq("/conf/httpd.conf"), eq("user-id"));
verify(Config.mockGroupPesistenceService).populateGroupWebServerTemplates(eq("HEALTH CHECK 4.0"), anyMap());
}
@Test
public void grantResalePermission_BrokerRevShareAtMP() throws Exception {
// given
OfferingType resaleType = OfferingType.BROKER;
setup(resaleType, false, false);
// when
resaleCopy = sppslBean.grantResalePermission(
productTemplate.getProductId(), supplier.getOrganizationId(),
grantee.getOrganizationId(), resaleType);
// then
verifyResaleCopy();
InOrder inOrder = inOrder(ds);
inOrder.verify(ds).persist(resaleCopy);
ArgumentCaptor<CatalogEntry> argCatEntry = ArgumentCaptor
.forClass(CatalogEntry.class);
inOrder.verify(ds, new Times(2)).persist(argCatEntry.capture());
verifyCreatedCatalogEntry(argCatEntry.getValue(), resaleType);
verifyImageResource();
}
@Test
public void shouldNotSendAMessageToDisabledClient() throws Exception {
// given
Object messageBody = new Object();
Notifier notifier = new DefaultNotifier();
AttachedClient attachedClient = mock(AttachedClient.class);
doReturn(false).when(attachedClient).isEnabled();
notifier.attachClient(attachedClient);
// when
notifier.sendMessage(messageBody);
// then
verify(attachedClient, new Times(0)).sendMessage(messageBody, notifier.getCallback());
assertThat(notifier.getAttachedClientsCount()).isEqualTo(1);
}
@Test
public void shouldSupportGlobPatternsInSourcePath() {
ArtifactPlan artifactPlan = new ArtifactPlan(ArtifactPlanType.unit, "**/*/a.log", "logs");
MergedTestArtifactPlan testArtifactPlan = new MergedTestArtifactPlan(artifactPlan);
File first = new File("target/test/report/a.log");
File second = new File("target/test/test/a/b/a.log");
first.mkdirs();
second.mkdirs();
testArtifactPlan.publishBuiltInArtifacts(mockArtifactPublisher, rootPath);
verify(mockArtifactPublisher).upload(first, "logs/report");
verify(mockArtifactPublisher).upload(second, "logs/test/a/b");
verify(mockArtifactPublisher, new Times(2)).upload(any(File.class), eq("testoutput"));
}
@Test
public void inUseDoesNothing() {
Mockito.when(inUseAttribute.get()).thenReturn(true);
UnusedChannelExceptionHandler.getInstance().exceptionCaught(ctx, exception);
Mockito.verify(ctx).fireExceptionCaught(exception);
Mockito.verify(ctx, new Times(0)).close();
}
@Test
public void releaseDoesntCloseIfNotFlagged() throws Exception {
ChannelPool channelPool = Mockito.mock(ChannelPool.class);
MockChannel channel = new MockChannel();
channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(false);
new HonorCloseOnReleaseChannelPool(channelPool).release(channel);
channel.runAllPendingTasks();
assertThat(channel.isOpen()).isTrue();
Mockito.verify(channelPool, new Times(0)).release(any());
Mockito.verify(channelPool, new Times(1)).release(any(), any());
}
@Test
public void releaseClosesIfFlagged() throws Exception {
ChannelPool channelPool = Mockito.mock(ChannelPool.class);
MockChannel channel = new MockChannel();
channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(true);
new HonorCloseOnReleaseChannelPool(channelPool).release(channel);
channel.runAllPendingTasks();
assertThat(channel.isOpen()).isFalse();
Mockito.verify(channelPool, new Times(0)).release(any());
Mockito.verify(channelPool, new Times(1)).release(any(), any());
}
@Test
public void grantResalePermission_ResellerRevShareAtMP() throws Exception {
// given
OfferingType resaleType = OfferingType.RESELLER;
setup(resaleType, false, false);
// when
resaleCopy = sppslBean.grantResalePermission(
productTemplate.getProductId(), supplier.getOrganizationId(),
grantee.getOrganizationId(), resaleType);
// then
verifyResaleCopy();
InOrder inOrder = inOrder(ds);
inOrder.verify(ds).persist(resaleCopy);
ArgumentCaptor<CatalogEntry> argCatEntry = ArgumentCaptor
.forClass(CatalogEntry.class);
inOrder.verify(ds, new Times(2)).persist(argCatEntry.capture());
verifyCreatedCatalogEntry(argCatEntry.getValue(), resaleType);
verifyImageResource();
verify(lsl).setLocalizedValues(resaleCopy.getKey(),
LocalizedObjectTypes.RESELLER_PRICEMODEL_LICENSE,
priceModelLicenses);
verify(spsl).copyDefaultPaymentEnablement(resaleCopy, grantee);
}
@Test
public void shouldCreateCorrectType() {
Timeout t = new Timeout(25, 50, mode);
assertCorrectMode(t.atLeastOnce(), Timeout.class, 50, 25, AtLeast.class);
assertCorrectMode(t.atLeast(5), Timeout.class, 50, 25, AtLeast.class);
assertCorrectMode(t.times(5), Timeout.class, 50, 25, Times.class);
assertCorrectMode(t.never(), Timeout.class, 50, 25, Times.class);
assertCorrectMode(t.only(), Timeout.class, 50, 25, Only.class);
assertCorrectMode(t.atMost(10), Timeout.class, 50, 25, AtMost.class);
}
@Test
public void should_create_correctly_configured_timeout() {
Timeout t = new Timeout(25, 50, mode);
assertTimeoutCorrectlyConfigured(t.atLeastOnce(), Timeout.class, 50, 25, AtLeast.class);
assertTimeoutCorrectlyConfigured(t.atLeast(5), Timeout.class, 50, 25, AtLeast.class);
assertTimeoutCorrectlyConfigured(t.times(5), Timeout.class, 50, 25, Times.class);
assertTimeoutCorrectlyConfigured(t.only(), Timeout.class, 50, 25, Only.class);
}
@Test
public void shouldCreateCompetingConsumersForSuppliedDependencyMaterialQueue() {
int numberOfConfigMaterialPostUpdateListeners = 3;
when(systemEnvironment.getNumberOfConfigMaterialPostUpdateListeners()).thenReturn(numberOfConfigMaterialPostUpdateListeners);
ConfigMaterialUpdateListenerFactory factory = new ConfigMaterialUpdateListenerFactory(systemEnvironment, configMaterialPostUpdateQueue,
null, null, null, null, null);
factory.init();
verify(configMaterialPostUpdateQueue, new Times(numberOfConfigMaterialPostUpdateListeners)).addListener(any(ConfigMaterialUpdateListener.class));
}
@Test
public void shouldCreateCompetingConsumersForSuppliedQueue() {
when(systemEnvironment.getNumberOfMaterialCheckListener()).thenReturn(NUMBER_OF_CONSUMERS);
MaterialUpdateListenerFactory factory = new MaterialUpdateListenerFactory(topic, queue, configQueue,
materialRepository, systemEnvironment, healthService, diskSpaceMonitor,
transactionTemplate, dependencyMaterialUpdater, scmMaterialUpdater,
packageMaterialUpdater, pluggableSCMMaterialUpdater, materialExpansionService, mduPerformanceLogger,
dependencyMaterialQueue, maintenanceModeService, configMaterialPostUpdateQueue, goConfigService);
factory.init();
verify(queue, new Times(NUMBER_OF_CONSUMERS)).addListener(any(GoMessageListener.class));
}
@Test
public void shouldCreateCompetingConsumersForSuppliedConfigQueue() {
when(systemEnvironment.getNumberOfConfigMaterialCheckListener()).thenReturn(NUMBER_OF_CONFIG_CONSUMERS);
MaterialUpdateListenerFactory factory = new MaterialUpdateListenerFactory(topic, queue, configQueue,
materialRepository, systemEnvironment, healthService, diskSpaceMonitor,
transactionTemplate, dependencyMaterialUpdater, scmMaterialUpdater,
packageMaterialUpdater, pluggableSCMMaterialUpdater, materialExpansionService, mduPerformanceLogger,
dependencyMaterialQueue, maintenanceModeService, configMaterialPostUpdateQueue, goConfigService);
factory.init();
verify(configQueue, new Times(NUMBER_OF_CONFIG_CONSUMERS)).addListener(any(GoMessageListener.class));
}
@Test
public void shouldCreateCompetingConsumersForSuppliedDependencyMaterialQueue() {
int noOfDependencyMaterialCheckListeners = 3;
when(systemEnvironment.getNumberOfDependencyMaterialUpdateListeners()).thenReturn(noOfDependencyMaterialCheckListeners);
MaterialUpdateListenerFactory factory = new MaterialUpdateListenerFactory(topic, queue, configQueue,
materialRepository, systemEnvironment, healthService, diskSpaceMonitor,
transactionTemplate, dependencyMaterialUpdater, scmMaterialUpdater,
packageMaterialUpdater, pluggableSCMMaterialUpdater, materialExpansionService, mduPerformanceLogger,
dependencyMaterialQueue, maintenanceModeService, configMaterialPostUpdateQueue, goConfigService);
factory.init();
verify(dependencyMaterialQueue, new Times(noOfDependencyMaterialCheckListeners)).addListener(any(GoMessageListener.class));
}
@Test
public void testCrawlSourceDirectories() throws Exception {
// Prepare the mock for this test
MessagesSourceCrawler messagesSourceCrawler = mock( MessagesSourceCrawler.class );
doCallRealMethod().when( messagesSourceCrawler ).setFilesToAvoid( any() );
doCallRealMethod().when( messagesSourceCrawler ).setSourceDirectories( any() );
doCallRealMethod().when( messagesSourceCrawler ).crawlSourceDirectories();
doNothing().when( messagesSourceCrawler ).lookForOccurrencesInFile( any(), any() );
messagesSourceCrawler
.setScanPhrases( new String[] { "Not relevant for this scenario!" } );
// Create and populate the filder to use in this test
List<String> sourceDirectories = new ArrayList<>();
sourceDirectories.add( temporaryFolder.getRoot().getPath() );
createDummyFiles( temporaryFolder,
new String[] { "a.txt", "b.txt", "c.txt", "d.txt", "a.java", "b.java", "c.java", "d.java" }, DUMMY_CONTENT );
messagesSourceCrawler.setSourceDirectories( sourceDirectories );
// The files set to be ignored
messagesSourceCrawler.setFilesToAvoid( Arrays.asList( "a.txt", "b.java", "c.java" ) );
// Test
messagesSourceCrawler.crawlSourceDirectories();
// Check results
verify( messagesSourceCrawler, new Times( 2 ) ).lookForOccurrencesInFile( any(), any() );
}
private void verifyNoRouting(String url, String controller, String action, H.Method... methods) {
for (H.Method method : methods) {
verify(mockRouter, new Times(0)).addMapping(method, url, "testapp.controller." + controller + "." + action, ACTION_ANNOTATION);
}
}
public Times inOrder() {
return VerificationModeFactory.times(times);
}
public Times inOrder() {
return VerificationModeFactory.times(times);
}