@Test public void testMultiClasses() { Class expectedClass1 = TestZuulFilter.class; Class expectedClass2 = TestZuulFilter2.class; when(configuration.getStringArray(eq("zuul.filters.classes"))).thenReturn(new String[]{"com.netflix.zuul.init.TestZuulFilter", "com.netflix.zuul.init2.TestZuulFilter2"}); when(configuration.getStringArray(eq("zuul.filters.packages"))).thenReturn(new String[0]); String[] classNames = module.findClassNames(configuration); assertThat(classNames.length, equalTo(2)); assertThat(classNames[0], equalTo(expectedClass1.getCanonicalName())); assertThat(classNames[1], equalTo(expectedClass2.getCanonicalName())); }
@Test void lazySingletonSupplierShouldOnlyRequestInstanceWhenRequired() { Object o = new Object(); Supplier<Object> mockSupplier = mock( Supplier.class ); when( mockSupplier.get() ).thenReturn( o ); Supplier<Object> supplier = Suppliers.lazySingleton( mockSupplier ); verifyZeroInteractions( mockSupplier ); assertThat( supplier.get(), sameInstance( o ) ); assertThat( supplier.get(), sameInstance( o ) ); assertThat( supplier.get(), sameInstance( o ) ); verify( mockSupplier ).get(); verifyNoMoreInteractions( mockSupplier ); }
@Test public void shouldPropagateReturnValueFromVisitFileFailed() throws IOException { for ( FileVisitResult result : FileVisitResult.values() ) { when( wrapped.visitFileFailed( any(), any() ) ).thenReturn( result ); assertThat( decorator.visitFileFailed( null, null ), is( result ) ); } }
@Test(dataProvider = "schedule") public void schedule(long nanos, int expired) { when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); for (int timeout : new int[] { 25, 90, 240 }) { timerWheel.schedule(new Timer(TimeUnit.SECONDS.toNanos(timeout))); } timerWheel.advance(nanos); verify(cache, times(expired)).evictEntry(any(), any(), anyLong()); for (Node<?, ?> node : captor.getAllValues()) { assertThat(node.getVariableTime(), is(lessThan(nanos))); } }
@Test public void shouldReturnItemIdFromFirstPresenter() { when(repositoryPresenter.getItemId(REPOSITORY_ITEM, 0)).thenReturn(10L); assertThat(repositoryAdapter.getItemId(0), is(10L + STATIC_ITEM_COUNT)); verify(secondRepositoryPresenter, never()).getItemId(any(), anyInt()); }
@Test void printsUnknownCommandWhenUnknownCommandIsProvided() { CommandLocator commandLocator = mock( CommandLocator.class ); when( commandLocator.getAllProviders() ).thenReturn( Collections.emptyList() ); when( commandLocator.findProvider( "foobar" ) ).thenThrow( new NoSuchElementException( "foobar" ) ); HelpCommand helpCommand = new HelpCommand( mock( Usage.class ), out, commandLocator ); IncorrectUsage incorrectUsage = assertThrows( IncorrectUsage.class, () -> helpCommand.execute( "foobar" ) ); assertThat( incorrectUsage.getMessage(), containsString( "Unknown command: foobar" ) ); }
@Test public void testSslQuorumProperty() { QuorumPeer qpMock = mock(QuorumPeer.class); QuorumBean qb = new QuorumBean(qpMock); when(qpMock.isSslQuorum()).thenReturn(true); assertThat("isSslQuorum property should return value of peer.isSslQuorum()", qb.isSslQuorum(), equalTo(true)); when(qpMock.isSslQuorum()).thenReturn(false); assertThat("isSslQuorum property should return value of peer.isSslQuorum()", qb.isSslQuorum(), equalTo(false)); }
@Test void nullToStringIsNotAllowed() { Object testValue = mock( Object.class ); when( testValue.toString() ).thenReturn( null ); IllegalArgumentException iae = assertThrows( IllegalArgumentException.class, () -> INSTANCE.validate( testValue ) ); assertThat( iae.getMessage(), containsString( "has null toString" ) ); }
@Test public void publishCreated() { registerAll(); dispatcher.publishCreated(cache, 1, 2); verify(createdListener, times(4)).onCreated(any()); assertThat(EventDispatcher.pending.get(), hasSize(2)); }
@Test public void shouldReturnEmptyListForFilterOfEmptyList() { final Predicate<String> predicate = mock(Predicate.class); when(predicate.apply(anyString())).thenReturn(true); final Function<List<String>, List<String>> function = functionFromListOf(String.class) .thenFilter(predicate); assertThat(function.apply(new ArrayList<String>()), sameInstance(Collections.<String>emptyList())); }
@Test public void expire_reschedule() { when(cache.evictEntry(captor.capture(), any(), anyLong())).thenAnswer(invocation -> { Timer timer = (Timer) invocation.getArgument(0); timer.setVariableTime(timerWheel.nanos + 100); return false; }); timerWheel.schedule(new Timer(100)); timerWheel.advance(TimerWheel.SPANS[0]); verify(cache).evictEntry(any(), any(), anyLong()); assertThat(captor.getValue().getNextInVariableOrder(), is(not(nullValue()))); assertThat(captor.getValue().getPreviousInVariableOrder(), is(not(nullValue()))); }
@Test public void reschedule() { when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); Timer timer = new Timer(TimeUnit.MINUTES.toNanos(15)); timerWheel.schedule(timer); Node<?, ?> startBucket = timer.getNextInVariableOrder(); timer.setVariableTime(TimeUnit.HOURS.toNanos(2)); timerWheel.reschedule(timer); assertThat(timer.getNextInVariableOrder(), is(not(startBucket))); timerWheel.advance(TimeUnit.DAYS.toNanos(1)); checkEmpty(); }
@CacheSpec(implementation = Implementation.Caffeine, population = Population.FULL, expiry = CacheExpiry.MOCKITO) @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void get_expiryFails_read(Cache<Integer, Integer> cache, CacheContext context) { try { context.ticker().advance(1, TimeUnit.HOURS); when(context.expiry().expireAfterRead(any(), any(), anyLong(), anyLong())) .thenThrow(ExpirationException.class); cache.get(context.firstKey(), identity()); } finally { context.ticker().advance(-1, TimeUnit.HOURS); assertThat(cache.asMap(), equalTo(context.original())); } }
@Test public void shouldSkipAfterFailedCheck() { when(mockPredicate.apply(anyListOf(Integer.class))).thenReturn(true); when(mockPredicate.apply(INITIAL_LIST)).thenReturn(false); final Repository<List<Integer>> repository = repositoryWithInitialValue(INITIAL_LIST) .observe() .onUpdatesPerLoop() .check(mockPredicate).orSkip() .thenGetFrom(otherListSource) .compile(); updatable.addToObservable(repository); assertThat(repository, has(INITIAL_LIST)); assertThat(updatable, wasNotUpdated()); }
@Test void shouldReportStoreSizes() throws Throwable { UdcInformationCollector collector = new DefaultUdcInformationCollector( Config.defaults(), dataSourceManager, usageData ); when( fileSystem.getFileSize( Mockito.any() ) ).thenReturn( 152L ); Map<String, String> udcParams = collector.getUdcParams(); assertThat( udcParams.get( "storesize" ), is( "152" ) ); }
@Test void shouldNotifyListenerOnRotationErrorDuringJobExecution() throws Exception { RotationListener rotationListener = mock( RotationListener.class ); Executor executor = mock( Executor.class ); RotatingFileOutputStreamSupplier supplier = new RotatingFileOutputStreamSupplier( fileSystem, logFile, 10, 0, 10, executor, rotationListener ); OutputStream outputStream = supplier.get(); RejectedExecutionException exception = new RejectedExecutionException( "text exception" ); doThrow( exception ).when( executor ).execute( any( Runnable.class ) ); write( supplier, "A string longer than 10 bytes" ); assertThat( supplier.get(), is( outputStream ) ); verify( rotationListener ).rotationError( exception, outputStream ); }
@Test public void asyncExpiry_completed() { AsyncExpiry<Integer, Integer> expiry = makeAsyncExpiry( ONE_MINUTE, 2 * ONE_MINUTE, 3 * ONE_MINUTE); CompletableFuture<Integer> future = CompletableFuture.completedFuture(100); assertThat(expiry.expireAfterCreate(0, future, 1L), is(ONE_MINUTE)); verify(expiry.delegate).expireAfterCreate(0, 100, 1L); assertThat(expiry.expireAfterUpdate(0, future, 1L, 2L), is(2 * ONE_MINUTE)); verify(expiry.delegate).expireAfterUpdate(0, 100, 1L, 2L); assertThat(expiry.expireAfterRead(0, future, 1L, 2L), is(3 * ONE_MINUTE)); verify(expiry.delegate).expireAfterRead(0, 100, 1L, 2L); }
@Test public void testTransformUserEntityCollection() { UserEntity mockUserEntityOne = mock(UserEntity.class); UserEntity mockUserEntityTwo = mock(UserEntity.class); List<UserEntity> userEntityList = new ArrayList<UserEntity>(5); userEntityList.add(mockUserEntityOne); userEntityList.add(mockUserEntityTwo); Collection<User> userCollection = userEntityDataMapper.transform(userEntityList); assertThat(userCollection.toArray()[0], is(instanceOf(User.class))); assertThat(userCollection.toArray()[1], is(instanceOf(User.class))); assertThat(userCollection.size(), is(2)); }
@Test public void trackPopulationJobs() { assertThat( jobController.getPopulationJobs(), is( empty() ) ); IndexPopulationJob populationJob = mock( IndexPopulationJob.class ); jobController.startIndexPopulation( populationJob ); assertThat( jobController.getPopulationJobs(), hasSize( 1 ) ); IndexPopulationJob populationJob2 = mock( IndexPopulationJob.class ); jobController.startIndexPopulation( populationJob2 ); assertThat( jobController.getPopulationJobs(), hasSize( 2 ) ); }