Best Mockito code snippet using org.mockitoutil.Conditions
Source:OffHeapDiskStoreTest.java
1/*2 * Copyright Terracotta, 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 org.ehcache.impl.internal.store.disk;17import org.ehcache.Cache;18import org.ehcache.CacheManager;19import org.ehcache.config.CacheConfiguration;20import org.ehcache.config.EvictionAdvisor;21import org.ehcache.config.ResourcePool;22import org.ehcache.config.ResourceType;23import org.ehcache.config.builders.CacheConfigurationBuilder;24import org.ehcache.config.builders.ResourcePoolsBuilder;25import org.ehcache.config.units.MemoryUnit;26import org.ehcache.core.spi.service.CacheManagerProviderService;27import org.ehcache.core.statistics.DefaultStatisticsService;28import org.ehcache.core.store.StoreConfigurationImpl;29import org.ehcache.spi.resilience.StoreAccessException;30import org.ehcache.core.statistics.LowerCachingTierOperationsOutcome;31import org.ehcache.CachePersistenceException;32import org.ehcache.expiry.ExpiryPolicy;33import org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration;34import org.ehcache.impl.internal.store.offheap.portability.AssertingOffHeapValueHolderPortability;35import org.ehcache.impl.internal.store.offheap.portability.OffHeapValueHolderPortability;36import org.ehcache.impl.internal.events.TestStoreEventDispatcher;37import org.ehcache.impl.internal.executor.OnDemandExecutionService;38import org.ehcache.impl.internal.persistence.TestDiskResourceService;39import org.ehcache.impl.internal.store.offheap.AbstractOffHeapStore;40import org.ehcache.impl.internal.store.offheap.AbstractOffHeapStoreTest;41import org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider;42import org.ehcache.core.spi.time.SystemTimeSource;43import org.ehcache.core.spi.time.TimeSource;44import org.ehcache.core.spi.ServiceLocator;45import org.ehcache.core.spi.store.Store;46import org.ehcache.impl.internal.util.UnmatchedResourceType;47import org.ehcache.spi.loaderwriter.CacheLoaderWriter;48import org.ehcache.spi.serialization.SerializationProvider;49import org.ehcache.spi.serialization.Serializer;50import org.ehcache.spi.serialization.UnsupportedTypeException;51import org.ehcache.core.spi.service.FileBasedPersistenceContext;52import org.ehcache.spi.persistence.PersistableResourceService.PersistenceSpaceIdentifier;53import org.ehcache.test.MockitoUtil;54import org.junit.Rule;55import org.junit.Test;56import org.junit.rules.TemporaryFolder;57import org.mockito.Answers;58import org.mockito.Mockito;59import org.terracotta.context.query.Matcher;60import org.terracotta.context.query.Query;61import org.terracotta.context.query.QueryBuilder;62import org.terracotta.statistics.OperationStatistic;63import java.io.IOException;64import java.io.Serializable;65import java.util.Arrays;66import java.util.Collections;67import java.util.HashSet;68import java.util.Map;69import java.util.Random;70import java.util.Set;71import java.util.concurrent.Callable;72import java.util.concurrent.ExecutorService;73import java.util.concurrent.Executors;74import java.util.concurrent.TimeUnit;75import static java.util.Collections.EMPTY_LIST;76import static java.util.Collections.singleton;77import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder;78import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder;79import static org.ehcache.config.builders.CacheManagerBuilder.persistence;80import static org.ehcache.config.builders.ExpiryPolicyBuilder.noExpiration;81import static org.ehcache.config.builders.ResourcePoolsBuilder.heap;82import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder;83import static org.ehcache.config.units.MemoryUnit.MB;84import static org.ehcache.core.spi.ServiceLocator.dependencySet;85import static org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration.DEFAULT_DISK_SEGMENTS;86import static org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration.DEFAULT_WRITER_CONCURRENCY;87import static org.ehcache.impl.internal.spi.TestServiceProvider.providerContaining;88import static org.ehcache.test.MockitoUtil.mock;89import static org.hamcrest.CoreMatchers.containsString;90import static org.hamcrest.CoreMatchers.notNullValue;91import static org.hamcrest.core.Is.is;92import static org.junit.Assert.assertThat;93import static org.junit.Assert.fail;94import static org.mockito.Mockito.mock;95import static org.mockito.Mockito.when;96import static org.terracotta.context.ContextManager.nodeFor;97import static org.terracotta.context.query.Matchers.attributes;98import static org.terracotta.context.query.Matchers.context;99import static org.terracotta.context.query.Matchers.hasAttribute;100public class OffHeapDiskStoreTest extends AbstractOffHeapStoreTest {101 @Rule102 public final TemporaryFolder temporaryFolder = new TemporaryFolder();103 @Rule104 public final TestDiskResourceService diskResourceService = new TestDiskResourceService();105 @Test106 public void testRecovery() throws StoreAccessException, IOException {107 OffHeapDiskStore<String, String> offHeapDiskStore = createAndInitStore(SystemTimeSource.INSTANCE,108 noExpiration());109 try {110 offHeapDiskStore.put("key1", "value1");111 assertThat(offHeapDiskStore.get("key1"), notNullValue());112 OffHeapDiskStore.Provider.close(offHeapDiskStore);113 OffHeapDiskStore.Provider.init(offHeapDiskStore);114 assertThat(offHeapDiskStore.get("key1"), notNullValue());115 } finally {116 destroyStore(offHeapDiskStore);117 }118 }119 @Test120 public void testRecoveryFailureWhenValueTypeChangesToIncompatibleClass() throws Exception {121 OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider();122 ServiceLocator serviceLocator = dependencySet().with(diskResourceService).with(provider)123 .with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS)).build();124 serviceLocator.startAllServices();125 CacheConfiguration<Long, String> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class);126 when(cacheConfiguration.getResourcePools())127 .thenReturn(newResourcePoolsBuilder().disk(1, MemoryUnit.MB, false).build());128 PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache",129 cacheConfiguration);130 {131 @SuppressWarnings("unchecked")132 Store.Configuration<Long, String> storeConfig1 = MockitoUtil.mock(Store.Configuration.class);133 when(storeConfig1.getKeyType()).thenReturn(Long.class);134 when(storeConfig1.getValueType()).thenReturn(String.class);135 when(storeConfig1.getResourcePools())136 .thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MB).build());137 when(storeConfig1.getDispatcherConcurrency()).thenReturn(1);138 OffHeapDiskStore<Long, String> offHeapDiskStore1 = provider.createStore(storeConfig1, space);139 provider.initStore(offHeapDiskStore1);140 destroyStore(offHeapDiskStore1);141 }142 {143 @SuppressWarnings("unchecked")144 Store.Configuration<Long, Serializable> storeConfig2 = MockitoUtil.mock(Store.Configuration.class);145 when(storeConfig2.getKeyType()).thenReturn(Long.class);146 when(storeConfig2.getValueType()).thenReturn(Serializable.class);147 when(storeConfig2.getResourcePools())148 .thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MB).build());149 when(storeConfig2.getDispatcherConcurrency()).thenReturn(1);150 when(storeConfig2.getClassLoader()).thenReturn(ClassLoader.getSystemClassLoader());151 OffHeapDiskStore<Long, Serializable> offHeapDiskStore2 = provider.createStore(storeConfig2, space);152 try {153 provider.initStore(offHeapDiskStore2);154 fail("expected IllegalArgumentException");155 } catch (IllegalArgumentException e) {156 // expected157 }158 destroyStore(offHeapDiskStore2);159 }160 }161 @Test162 public void testRecoveryWithArrayType() throws Exception {163 OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider();164 ServiceLocator serviceLocator = dependencySet().with(diskResourceService).with(provider)165 .with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS)).build();166 serviceLocator.startAllServices();167 CacheConfiguration<?, ?> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class);168 when(cacheConfiguration.getResourcePools())169 .thenReturn(newResourcePoolsBuilder().disk(1, MemoryUnit.MB, false).build());170 PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache",171 cacheConfiguration);172 {173 @SuppressWarnings("unchecked")174 Store.Configuration<Long, Object[]> storeConfig1 = MockitoUtil.mock(Store.Configuration.class);175 when(storeConfig1.getKeyType()).thenReturn(Long.class);176 when(storeConfig1.getValueType()).thenReturn(Object[].class);177 when(storeConfig1.getResourcePools())178 .thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MB).build());179 when(storeConfig1.getDispatcherConcurrency()).thenReturn(1);180 OffHeapDiskStore<Long, Object[]> offHeapDiskStore1 = provider.createStore(storeConfig1, space);181 provider.initStore(offHeapDiskStore1);182 destroyStore(offHeapDiskStore1);183 }184 {185 @SuppressWarnings("unchecked")186 Store.Configuration<Long, Object[]> storeConfig2 = MockitoUtil.mock(Store.Configuration.class);187 when(storeConfig2.getKeyType()).thenReturn(Long.class);188 when(storeConfig2.getValueType()).thenReturn(Object[].class);189 when(storeConfig2.getResourcePools())190 .thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MB).build());191 when(storeConfig2.getDispatcherConcurrency()).thenReturn(1);192 when(storeConfig2.getClassLoader()).thenReturn(ClassLoader.getSystemClassLoader());193 OffHeapDiskStore<Long, Object[]> offHeapDiskStore2 = provider.createStore(storeConfig2, space);194 provider.initStore(offHeapDiskStore2);195 destroyStore(offHeapDiskStore2);196 }197 }198 @Test199 public void testProvidingOffHeapDiskStoreConfiguration() throws Exception {200 OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider();201 ServiceLocator serviceLocator = dependencySet().with(diskResourceService).with(provider)202 .with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS)).build();203 serviceLocator.startAllServices();204 CacheConfiguration<?, ?> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class);205 when(cacheConfiguration.getResourcePools())206 .thenReturn(newResourcePoolsBuilder().disk(1, MemoryUnit.MB, false).build());207 PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache",208 cacheConfiguration);209 @SuppressWarnings("unchecked")210 Store.Configuration<Long, Object[]> storeConfig1 = MockitoUtil.mock(Store.Configuration.class);211 when(storeConfig1.getKeyType()).thenReturn(Long.class);212 when(storeConfig1.getValueType()).thenReturn(Object[].class);213 when(storeConfig1.getResourcePools())214 .thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MB).build());215 when(storeConfig1.getDispatcherConcurrency()).thenReturn(1);216 OffHeapDiskStore<Long, Object[]> offHeapDiskStore1 = provider.createStore(storeConfig1, space,217 new OffHeapDiskStoreConfiguration("pool", 2, 4));218 assertThat(offHeapDiskStore1.getThreadPoolAlias(), is("pool"));219 assertThat(offHeapDiskStore1.getWriterConcurrency(), is(2));220 assertThat(offHeapDiskStore1.getDiskSegments(), is(4));221 }222 @Override223 protected OffHeapDiskStore<String, String> createAndInitStore(final TimeSource timeSource,224 final ExpiryPolicy<? super String, ? super String> expiry) {225 try {226 SerializationProvider serializationProvider = new DefaultSerializationProvider(null);227 serializationProvider.start(providerContaining(diskResourceService));228 ClassLoader classLoader = getClass().getClassLoader();229 Serializer<String> keySerializer = serializationProvider.createKeySerializer(String.class, classLoader);230 Serializer<String> valueSerializer = serializationProvider.createValueSerializer(String.class, classLoader);231 StoreConfigurationImpl<String, String> storeConfiguration = new StoreConfigurationImpl<>(String.class,232 String.class, null, classLoader, expiry, null, 0, true, keySerializer, valueSerializer, null,233 false);234 OffHeapDiskStore<String, String> offHeapStore = new OffHeapDiskStore<String, String>(235 getPersistenceContext(), new OnDemandExecutionService(), null, DEFAULT_WRITER_CONCURRENCY,236 DEFAULT_DISK_SEGMENTS, storeConfiguration, timeSource, new TestStoreEventDispatcher<>(),237 MB.toBytes(1), new DefaultStatisticsService()) {238 @Override239 protected OffHeapValueHolderPortability<String> createValuePortability(Serializer<String> serializer) {240 return new AssertingOffHeapValueHolderPortability<>(serializer);241 }242 };243 OffHeapDiskStore.Provider.init(offHeapStore);244 return offHeapStore;245 } catch (UnsupportedTypeException e) {246 throw new AssertionError(e);247 }248 }249 /*250 * @Override protected OffHeapDiskStore<String, byte[]>251 * createAndInitStore(TimeSource timeSource, ExpiryPolicy<? super String, ?252 * super byte[]> expiry, EvictionAdvisor<? super String, ? super byte[]>253 * evictionAdvisor) { try { SerializationProvider serializationProvider = new254 * DefaultSerializationProvider(null);255 * serializationProvider.start(providerContaining(diskResourceService));256 * ClassLoader classLoader = getClass().getClassLoader(); Serializer<String>257 * keySerializer = serializationProvider.createKeySerializer(String.class,258 * classLoader); Serializer<byte[]> valueSerializer =259 * serializationProvider.createValueSerializer(byte[].class, classLoader);260 * StoreConfigurationImpl<String, byte[]> storeConfiguration = new261 * StoreConfigurationImpl<>(String.class, byte[].class, evictionAdvisor,262 * getClass().getClassLoader(), expiry, null, 0, true, keySerializer,263 * valueSerializer, null, false); OffHeapDiskStore<String, byte[]> offHeapStore264 * = new OffHeapDiskStore<String, byte[]>( getPersistenceContext(), new265 * OnDemandExecutionService(), null, DEFAULT_WRITER_CONCURRENCY,266 * DEFAULT_DISK_SEGMENTS, storeConfiguration, timeSource, new267 * TestStoreEventDispatcher<>(), MB.toBytes(1), new DefaultStatisticsService())268 * {269 * 270 * @Override protected OffHeapValueHolderPortability<byte[]>271 * createValuePortability(Serializer<byte[]> serializer) { return new272 * AssertingOffHeapValueHolderPortability<>(serializer); } };273 * OffHeapDiskStore.Provider.init(offHeapStore); return offHeapStore; } catch274 * (UnsupportedTypeException e) { throw new AssertionError(e); } }275 */276 @Override277 protected void destroyStore(AbstractOffHeapStore<?, ?> store) {278 try {279 OffHeapDiskStore.Provider.close((OffHeapDiskStore<?, ?>) store);280 } catch (IOException e) {281 throw new AssertionError(e);282 }283 }284 @Test285 public void testStoreInitFailsWithoutLocalPersistenceService() throws Exception {286 OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider();287 try {288 dependencySet().with(provider).build();289 fail("IllegalStateException expected");290 } catch (IllegalStateException e) {291 assertThat(e.getMessage(),292 containsString("Failed to find provider with satisfied dependency set for interface"293 + " org.ehcache.core.spi.service.DiskResourceService"));294 }295 }296 @Test297 @SuppressWarnings("unchecked")298 public void testAuthoritativeRank() throws Exception {299 OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider();300 assertThat(provider.rankAuthority(ResourceType.Core.DISK, EMPTY_LIST), is(1));301 assertThat(provider.rankAuthority(new UnmatchedResourceType(), EMPTY_LIST), is(0));302 }303 @Test304 public void testRank() throws Exception {305 OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider();306 assertRank(provider, 1, ResourceType.Core.DISK);307 assertRank(provider, 0, ResourceType.Core.HEAP);308 assertRank(provider, 0, ResourceType.Core.OFFHEAP);309 assertRank(provider, 0, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP);310 assertRank(provider, 0, ResourceType.Core.DISK, ResourceType.Core.HEAP);311 assertRank(provider, 0, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);312 assertRank(provider, 0, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);313 assertRank(provider, 0, (ResourceType<ResourcePool>) new UnmatchedResourceType());314 assertRank(provider, 0, ResourceType.Core.DISK, new UnmatchedResourceType());315 }316 private void assertRank(final Store.Provider provider, final int expectedRank, final ResourceType<?>... resources) {317 assertThat(provider.rank(new HashSet<>(Arrays.asList(resources)), Collections.emptyList()), is(expectedRank));318 }319 private FileBasedPersistenceContext getPersistenceContext() {320 try {321 CacheConfiguration<?, ?> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class);322 when(cacheConfiguration.getResourcePools())323 .thenReturn(newResourcePoolsBuilder().disk(1, MB, false).build());324 PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache",325 cacheConfiguration);326 return diskResourceService.createPersistenceContextWithin(space, "store");327 } catch (CachePersistenceException e) {328 throw new AssertionError(e);329 }330 }331 @Test332 public void diskStoreShrinkingTest() throws Exception {333 try (CacheManager manager = newCacheManagerBuilder()334 .with(persistence(temporaryFolder.newFolder("disk-stores").getAbsolutePath())).build(true)) {335 CacheConfigurationBuilder<Long, CacheValue> cacheConfigurationBuilder = newCacheConfigurationBuilder(336 Long.class, CacheValue.class, heap(1000).offheap(10, MB).disk(20, MB))337 .withLoaderWriter(new CacheLoaderWriter<Long, CacheValue>() {338 @Override339 public CacheValue load(Long key) {340 return null;341 }342 @Override343 public Map<Long, CacheValue> loadAll(Iterable<? extends Long> keys) {344 return Collections.emptyMap();345 }346 @Override347 public void write(Long key, CacheValue value) {348 }349 @Override350 public void writeAll(351 Iterable<? extends Map.Entry<? extends Long, ? extends CacheValue>> entries) {352 }353 @Override354 public void delete(Long key) {355 }356 @Override357 public void deleteAll(Iterable<? extends Long> keys) {358 }359 });360 Cache<Long, CacheValue> cache = manager.createCache("test", cacheConfigurationBuilder);361 for (long i = 0; i < 100000; i++) {362 cache.put(i, new CacheValue((int) i));363 }364 Callable<Void> task = () -> {365 Random rndm = new Random();366 long start = System.nanoTime();367 while (System.nanoTime() < start + TimeUnit.SECONDS.toNanos(5)) {368 Long k = key(rndm);369 switch (rndm.nextInt(4)) {370 case 0: {371 CacheValue v = value(rndm);372 cache.putIfAbsent(k, v);373 break;374 }375 case 1: {376 CacheValue nv = value(rndm);377 CacheValue ov = value(rndm);378 cache.put(k, ov);379 cache.replace(k, nv);380 break;381 }382 case 2: {383 CacheValue nv = value(rndm);384 CacheValue ov = value(rndm);385 cache.put(k, ov);386 cache.replace(k, ov, nv);387 break;388 }389 case 3: {390 CacheValue v = value(rndm);391 cache.put(k, v);392 cache.remove(k, v);393 break;394 }395 }396 }397 return null;398 };399 ExecutorService executor = Executors.newCachedThreadPool();400 try {401 executor.invokeAll(Collections.nCopies(4, task));402 } finally {403 executor.shutdown();404 }405 Query invalidateAllQuery = QueryBuilder.queryBuilder().descendants()406 .filter(context(attributes(hasAttribute("tags", new Matcher<Set<String>>() {407 @Override408 protected boolean matchesSafely(Set<String> object) {409 return object.contains("OffHeap");410 }411 })))).filter(context(attributes(hasAttribute("name", "invalidateAll")))).ensureUnique().build();412 @SuppressWarnings("unchecked")413 OperationStatistic<LowerCachingTierOperationsOutcome.InvalidateAllOutcome> invalidateAll = (OperationStatistic<LowerCachingTierOperationsOutcome.InvalidateAllOutcome>) invalidateAllQuery414 .execute(singleton(nodeFor(cache))).iterator().next().getContext().attributes().get("this");415 assertThat(invalidateAll.sum(), is(0L));416 }417 }418 private Long key(Random rndm) {419 return (long) rndm.nextInt(100000);420 }421 private CacheValue value(Random rndm) {422 return new CacheValue(rndm.nextInt(100000));423 }424 public static class CacheValue implements Serializable {425 private static final long serialVersionUID = 1L;426 private final int value;427 private final byte[] padding;428 public CacheValue(int value) {429 this.value = value;430 this.padding = new byte[800];431 }432 @Override433 public int hashCode() {434 return value;435 }436 public boolean equals(Object o) {437 if (o instanceof CacheValue) {438 return value == ((CacheValue) o).value;439 } else {440 return false;441 }442 }443 }444 @Override445 protected AbstractOffHeapStore<String, byte[]> createAndInitStore(TimeSource timeSource,446 ExpiryPolicy<? super String, ? super byte[]> expiry,447 EvictionAdvisor<? super String, ? super byte[]> evictionAdvisor) {448 // TODO Auto-generated method stub449 return null;450 }451}...
Source:ByteArrayUploadDataProviderTest.java
1/*2 * Copyright (C) 2016 The Android Open Source Project3 *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.google.android.exoplayer2.ext.cronet;17import static org.junit.Assert.assertArrayEquals;18import static org.junit.Assert.assertEquals;19import static org.mockito.Mockito.times;20import static org.mockito.Mockito.verify;21import android.support.test.InstrumentationRegistry;22import android.support.test.runner.AndroidJUnit4;23import com.google.android.exoplayer2.testutil.MockitoUtil;24import java.io.IOException;25import java.nio.ByteBuffer;26import java.util.Arrays;27import org.chromium.net.UploadDataSink;28import org.junit.Before;29import org.junit.Test;30import org.junit.runner.RunWith;31import org.mockito.Mock;32/**33 * Tests for {@link ByteArrayUploadDataProvider}.34 */35@RunWith(AndroidJUnit4.class)36public final class ByteArrayUploadDataProviderTest {37 private static final byte[] TEST_DATA = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};38 @Mock private UploadDataSink mockUploadDataSink;39 private ByteBuffer byteBuffer;40 private ByteArrayUploadDataProvider byteArrayUploadDataProvider;41 @Before42 public void setUp() {43 MockitoUtil.setUpMockito(InstrumentationRegistry.getTargetContext(), this);44 byteBuffer = ByteBuffer.allocate(TEST_DATA.length);45 byteArrayUploadDataProvider = new ByteArrayUploadDataProvider(TEST_DATA);46 }47 @Test48 public void testGetLength() {49 assertEquals(TEST_DATA.length, byteArrayUploadDataProvider.getLength());50 }51 @Test52 public void testReadFullBuffer() throws IOException {53 byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);54 assertArrayEquals(TEST_DATA, byteBuffer.array());55 }56 @Test57 public void testReadPartialBuffer() throws IOException {58 byte[] firstHalf = Arrays.copyOfRange(TEST_DATA, 0, TEST_DATA.length / 2);59 byte[] secondHalf = Arrays.copyOfRange(TEST_DATA, TEST_DATA.length / 2, TEST_DATA.length);60 byteBuffer = ByteBuffer.allocate(TEST_DATA.length / 2);61 // Read half of the data.62 byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);63 assertArrayEquals(firstHalf, byteBuffer.array());64 // Read the second half of the data.65 byteBuffer.rewind();66 byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);67 assertArrayEquals(secondHalf, byteBuffer.array());68 verify(mockUploadDataSink, times(2)).onReadSucceeded(false);69 }70 @Test71 public void testRewind() throws IOException {72 // Read all the data.73 byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);74 assertArrayEquals(TEST_DATA, byteBuffer.array());75 // Rewind and make sure it can be read again.76 byteBuffer.clear();77 byteArrayUploadDataProvider.rewind(mockUploadDataSink);78 byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);79 assertArrayEquals(TEST_DATA, byteBuffer.array());80 verify(mockUploadDataSink).onRewindSucceeded();81 }82}...
Source:DefaultResilienceStrategyProviderFactoryTest.java
1/**2 * Copyright Terracotta, 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 org.ehcache.impl.internal.spi.resilience;17import org.ehcache.config.CacheConfiguration;18import org.ehcache.impl.config.resilience.DefaultResilienceStrategyProviderConfiguration;19import org.ehcache.spi.resilience.RecoveryStore;20import org.ehcache.spi.resilience.ResilienceStrategy;21import org.ehcache.spi.resilience.ResilienceStrategyProvider;22import org.ehcache.spi.service.ServiceCreationConfiguration;23import org.ehcache.test.MockitoUtil;24import org.hamcrest.core.IsNull;25import org.hamcrest.core.IsSame;26import org.junit.Assert;27import org.junit.Test;28public class DefaultResilienceStrategyProviderFactoryTest {29 @Test30 public void testNullGivesValidFactory() {31 ResilienceStrategyProvider provider = new DefaultResilienceStrategyProviderFactory().create(null);32 Assert.assertThat(provider.createResilienceStrategy("test", MockitoUtil.mock(CacheConfiguration.class), MockitoUtil.mock(RecoveryStore.class)), IsNull.notNullValue());33 }34 @Test35 public void testWrongConfigTypeFails() {36 try {37 new DefaultResilienceStrategyProviderFactory().create(MockitoUtil.mock(ServiceCreationConfiguration.class));38 Assert.fail("Expected IllegalArgumentException");39 } catch (IllegalArgumentException e) {40 // expected41 }42 }43 @Test44 public void testSpecifiedConfigIsPassed() {45 ResilienceStrategy<?, ?> resilienceStrategy = MockitoUtil.mock(ResilienceStrategy.class);46 DefaultResilienceStrategyProviderConfiguration configuration = new DefaultResilienceStrategyProviderConfiguration();47 configuration.setDefaultResilienceStrategy(resilienceStrategy);48 ResilienceStrategyProvider provider = new DefaultResilienceStrategyProviderFactory().create(configuration);49 Assert.assertThat(provider.createResilienceStrategy("foo", MockitoUtil.mock(CacheConfiguration.class), MockitoUtil.mock(RecoveryStore.class)), IsSame.sameInstance(resilienceStrategy));50 }51}...
Source:BridgeMethodPuzzleTest.java
...5package org.mockitousage.puzzlers;6import static org.junit.Assert.assertEquals;7import static org.mockito.Mockito.mock;8import static org.mockito.Mockito.verify;9import static org.mockitoutil.Conditions.bridgeMethod;10import org.assertj.core.api.Assertions;11import org.junit.Test;12import org.mockitoutil.TestBase;13/**14 * Bridge method is generated by compiler when erasure in parent class is15 * different. When is different then it means that in runtime we will have16 * overloading rather than overridding Therefore the compiler generates bridge17 * method in Subclass so that erasures are the same, signatures of methods match18 * and overridding is ON.19 */20@SuppressWarnings("unchecked")21public class BridgeMethodPuzzleTest extends TestBase {22 private class Super<T> {23 public String say(T t) {...
Source:MockitoUtil.java
1/*2 * Copyright Terracotta, 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 org.ehcache.test;17import org.mockito.Mockito;18/**19 * Tiny little class allowing to remove the type constraint between the parameter and the return type. That way,20 * mocking a generic type won't be a systematic warning anymore.21 * <pre>{@code22 * List<String> list = MockitoUtil.mock(List.class); // no suppress warning23 * }24 * </pre>25 */26public final class MockitoUtil {27 private MockitoUtil() {28 }29 @SuppressWarnings("unchecked")30 public static <T> T mock(Class<?> clazz) {31 return Mockito.mock((Class<T>) clazz);32 }33}...
Conditions
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.junit.runners.JUnit4;4import org.mockitoutil.Conditions;5import static org.junit.Assert.*;6@RunWith(JUnit4.class)7public class TestConditions {8 public void testConditions() {9 Conditions conditions = new Conditions();10 conditions.add("one");11 conditions.add("two");12 conditions.add("three");13 assertTrue(conditions.contains("one"));14 assertTrue(conditions.contains("two"));15 assertTrue(conditions.contains("three"));16 assertFalse(conditions.contains("four"));17 assertFalse(conditions.contains("five"));18 assertFalse(conditions.contains("six"));19 }20}21java -cp .;junit-4.12.jar;mockito-all-1.10.19.jar org.junit.runner.JUnitCore 122OK (1 test)
Conditions
Using AI Code Generation
1import org.junit.Test;2import org.mockitoutil.Conditions;3import static org.junit.Assert.*;4public class ConditionsTest {5 public void testConditions() {6 assertTrue(Conditions.isOdd().matches(1));7 assertFalse(Conditions.isOdd().matches(2));8 assertTrue(Conditions.isEven().matches(2));9 assertFalse(Conditions.isEven().matches(1));10 }11}
Conditions
Using AI Code Generation
1package org.mockitoutil;2import org.mockito.Mockito;3public class Conditions {4 public static <T> T eq(T obj) {5 return Mockito.argThat(new EqualsCondition<T>(obj));6 }7 public static <T> T isNull() {8 return Mockito.argThat(new IsNullCondition<T>());9 }10 public static <T> T isNotNull() {11 return Mockito.argThat(new IsNotNullCondition<T>());12 }13 public static <T> T isA(Class<T> clazz) {14 return Mockito.argThat(new IsACondition<T>(clazz));15 }16}17package org.mockitoutil;18import org.mockito.Mockito;19public class Conditions {20 public static <T> T eq(T obj) {21 return Mockito.argThat(new EqualsCondition<T>(obj));22 }23 public static <T> T isNull() {24 return Mockito.argThat(new IsNullCondition<T>());25 }26 public static <T> T isNotNull() {27 return Mockito.argThat(new IsNotNullCondition<T>());28 }29 public static <T> T isA(Class<T> clazz) {30 return Mockito.argThat(new IsACondition<T>(clazz));31 }32}33package org.mockitoutil;34import org.mockito.Mockito;35public class Conditions {36 public static <T> T eq(T obj) {37 return Mockito.argThat(new EqualsCondition<T>(obj));38 }39 public static <T> T isNull() {40 return Mockito.argThat(new IsNullCondition<T>());41 }42 public static <T> T isNotNull() {43 return Mockito.argThat(new IsNotNullCondition<T>());44 }45 public static <T> T isA(Class<T> clazz) {46 return Mockito.argThat(new IsACondition<T>(clazz));47 }48}49package org.mockitoutil;50import org.mockito.Mockito;51public class Conditions {52 public static <T> T eq(T obj) {53 return Mockito.argThat(new EqualsCondition<T>(obj));54 }55 public static <T> T isNull() {56 return Mockito.argThat(new IsNullCondition<T>());57 }58 public static <T> T isNotNull() {
Conditions
Using AI Code Generation
1public class ConditionsTest {2 public void testConditions() {3 Conditions conditions = new Conditions();4 conditions.add("first");5 conditions.add("second");6 conditions.add("third");7 conditions.add("fourth");8 assertTrue(conditions.contains("first"));9 assertTrue(conditions.contains("second"));10 assertTrue(conditions.contains("third"));11 assertTrue(conditions.contains("fourth"));12 conditions.remove("second");13 assertTrue(conditions.contains("first"));14 assertFalse(conditions.contains("second"));15 assertTrue(conditions.contains("third"));16 assertTrue(conditions.contains("fourth"));17 }18}19public class ConditionsTest {20 public void testConditions() {21 Conditions conditions = new Conditions();22 conditions.add("first");23 conditions.add("second");24 conditions.add("third");25 conditions.add("fourth");26 assertTrue(conditions.contains("first"));27 assertTrue(conditions.contains("second"));28 assertTrue(conditions.contains("third"));29 assertTrue(conditions.contains("fourth"));30 conditions.remove("second");31 assertTrue(conditions.contains("first"));32 assertFalse(conditions.contains("second"));33 assertTrue(conditions.contains("third"));34 assertTrue(conditions.contains("fourth"));35 }36}37public class ConditionsTest {38 public void testConditions() {39 Conditions conditions = new Conditions();40 conditions.add("first");41 conditions.add("second");42 conditions.add("third");43 conditions.add("fourth");44 assertTrue(conditions.contains("first"));45 assertTrue(conditions.contains("second"));46 assertTrue(conditions.contains("third"));47 assertTrue(conditions.contains("fourth"));48 conditions.remove("second");49 assertTrue(conditions.contains("first"));50 assertFalse(conditions.contains("second"));51 assertTrue(conditions.contains("third"));52 assertTrue(conditions.contains("fourth"));53 }54}55public class ConditionsTest {56 public void testConditions() {57 Conditions conditions = new Conditions();58 conditions.add("first");59 conditions.add("second");60 conditions.add("third");61 conditions.add("fourth");62 assertTrue(conditions.contains("first"));63 assertTrue(conditions.contains("second"));64 assertTrue(conditions.contains
Conditions
Using AI Code Generation
1import org.mockitoutil.*;2public class 1 {3 public static void main(String args[]) {4 Conditions c = new Conditions();5 c.setCondition(1);6 c.setCondition(2);7 c.setCondition(3);8 c.setCondition(4);9 c.setCondition(5);10 c.setCondition(6);11 c.setCondition(7);12 c.setCondition(8);13 c.setCondition(9);14 c.setCondition(10);15 c.setCondition(11);16 c.setCondition(12);17 c.setCondition(13);18 c.setCondition(14);19 c.setCondition(15);20 c.setCondition(16);21 c.setCondition(17);22 c.setCondition(18);23 c.setCondition(19);24 c.setCondition(20);25 c.setCondition(21);26 c.setCondition(22);27 c.setCondition(23);28 c.setCondition(24);29 c.setCondition(25);30 c.setCondition(26);31 c.setCondition(27);32 c.setCondition(28);33 c.setCondition(29);34 c.setCondition(30);35 c.setCondition(31);36 c.setCondition(32);37 c.setCondition(33);38 c.setCondition(34);39 c.setCondition(35);40 c.setCondition(36);41 c.setCondition(37);42 c.setCondition(38);43 c.setCondition(39);44 c.setCondition(40);45 c.setCondition(41);46 c.setCondition(42);47 c.setCondition(43);48 c.setCondition(44);49 c.setCondition(45);50 c.setCondition(46);51 c.setCondition(47);52 c.setCondition(48);53 c.setCondition(49);54 c.setCondition(50);55 c.setCondition(51);56 c.setCondition(52);57 c.setCondition(53);58 c.setCondition(54);59 c.setCondition(55);60 c.setCondition(56);61 c.setCondition(57);62 c.setCondition(58);63 c.setCondition(59);64 c.setCondition(60);65 c.setCondition(61);66 c.setCondition(62);67 c.setCondition(63);68 c.setCondition(64);69 c.setCondition(65);70 c.setCondition(66);71 c.setCondition(67);
Conditions
Using AI Code Generation
1import org.mockitoutil.Conditions;2import org.junit.Test;3import static org.junit.Assert.*;4public class ConditionsTest {5 public void testConditions() {6 assertTrue(Conditions.isTest(Conditions.class));7 assertFalse(Conditions.isTest(ConditionsTest.class));8 }9}10import org.powermock.modules.junit4.rule.Conditions;11import org.junit.Test;12import static org.junit.Assert.*;13public class ConditionsTest {14 public void testConditions() {15 assertTrue(Conditions.isTest(Conditions.class));16 assertFalse(Conditions.isTest(ConditionsTest.class));17 }18}19import org.mockito.internal.matchers.Conditions;20import org.junit.Test;21import static org.junit.Assert.*;22public class ConditionsTest {23 public void testConditions() {24 assertTrue(Conditions.isTest(Conditions.class));25 assertFalse(Conditions.isTest(ConditionsTest.class));26 }27}28import org.mockito.internal.matchers.text.Conditions;29import org.junit.Test;30import static org.junit.Assert.*;31public class ConditionsTest {32 public void testConditions() {33 assertTrue(Conditions.isTest(Conditions.class));34 assertFalse(Conditions.isTest(ConditionsTest.class));35 }36}37import org.mockito.internal.matchers.text.Conditions;38import org.junit.Test;39import static org.junit.Assert.*;40public class ConditionsTest {41 public void testConditions() {42 assertTrue(Conditions.isTest(Conditions.class));43 assertFalse(Conditions.isTest(ConditionsTest.class));44 }45}46import org.mockito.internal.matchers.text.Conditions;47import org.junit.Test;48import static org.junit.Assert.*;49public class ConditionsTest {50 public void testConditions() {51 assertTrue(Conditions.isTest(Conditions.class));52 assertFalse(Conditions.isTest(ConditionsTest.class));53 }54}55import org
Conditions
Using AI Code Generation
1package org.mockitoutil;2import org.junit.Test;3import org.mockito.Mockito;4import static org.junit.Assert.*;5import static org.mockito.Mockito.*;6public class ConditionsTest {7 public void shouldTestConditions() {8 Conditions conditions = new Conditions();9 boolean result = conditions.test(true, false);10 assertFalse(result);11 }12 public void shouldTestConditions2() {13 Conditions conditions = new Conditions();14 boolean result = conditions.test(false, false);15 assertTrue(result);16 }17}18package org.mockito;19import org.junit.Test;20import org.mockito.Mockito;21import static org.junit.Assert.*;22import static org.mockito.Mockito.*;23public class ConditionsTest {24 public void shouldTestConditions() {25 Conditions conditions = new Conditions();26 boolean result = conditions.test(true, false);27 assertFalse(result);28 }29 public void shouldTestConditions2() {30 Conditions conditions = new Conditions();31 boolean result = conditions.test(false, false);32 assertTrue(result);33 }34}
Conditions
Using AI Code Generation
1public class ConditionsTest {2 public void testConditions() {3 Conditions conditions = new Conditions();4 conditions.add("1");5 conditions.add("2");6 conditions.add("3");7 conditions.add(1);8 conditions.add(2);9 conditions.add(3);10 conditions.add(4);11 conditions.add(5);12 conditions.add(6);13 conditions.add(7);14 conditions.add(8);15 conditions.add(9);16 conditions.add(10);17 conditions.add(11);18 conditions.add(12);19 conditions.add(13);20 conditions.add(14);21 conditions.add(15);22 conditions.add(16);23 conditions.add(17);24 conditions.add(18);25 conditions.add(19);26 conditions.add(20);27 conditions.add(21);28 conditions.add(22);29 conditions.add(23);30 conditions.add(24);31 conditions.add(25);32 conditions.add(26);33 conditions.add(27);34 conditions.add(28);35 conditions.add(29);36 conditions.add(30);37 conditions.add(31);38 conditions.add(32);39 conditions.add(33);40 conditions.add(34);41 conditions.add(35);42 conditions.add(36);43 conditions.add(37);44 conditions.add(38);45 conditions.add(39);46 conditions.add(40);47 conditions.add(41);48 conditions.add(42);49 conditions.add(43);50 conditions.add(44);51 conditions.add(45);52 conditions.add(46);53 conditions.add(47);54 conditions.add(48);55 conditions.add(49);56 conditions.add(50);57 conditions.add(51);58 conditions.add(52);59 conditions.add(53);60 conditions.add(54);61 conditions.add(55);62 conditions.add(56);63 conditions.add(57);64 conditions.add(58);65 conditions.add(59);66 conditions.add(60);67 conditions.add(61);68 conditions.add(62);69 conditions.add(63);70 conditions.add(64);71 conditions.add(65);72 conditions.add(66);73 conditions.add(67);74 conditions.add(68);75 conditions.add(69);76 conditions.add(70);77 conditions.add(71);78 conditions.add(72);79 conditions.add(73);80 conditions.add(74);81 conditions.add(75);82 conditions.add(76);
Conditions
Using AI Code Generation
1import org.mockitoutil.*;2public class ConditionsTest {3 public static void main(String[] args) {4 Conditions conditions = new Conditions();5 boolean result = conditions.isNotEqual(2, 3);6 System.out.println("result = " + result);7 }8}9import org.mockitoutil.*;10public class ConditionsTest {11 public static void main(String[] args) {12 Conditions conditions = new Conditions();13 boolean result = conditions.isEqual(2, 2);14 System.out.println("result = " + result);15 }16}
Conditions
Using AI Code Generation
1Conditions multipleOf3 = new Conditions() {2 public boolean isSatisfied(Object value) {3 return (Integer) value % 3 == 0;4 }5};6Conditions multipleOf5 = new Conditions() {7 public boolean isSatisfied(Object value) {8 return (Integer) value % 5 == 0;9 }10};11Conditions multipleOf3And5 = multipleOf3.and(multipleOf5);12Conditions multipleOf3Or5 = multipleOf3.or(multipleOf5);13Conditions notMultipleOf3 = multipleOf3.not();14Conditions notMultipleOf5 = multipleOf5.not();15Conditions notMultipleOf3And5 = multipleOf3And5.not();16Conditions notMultipleOf3Or5 = multipleOf3Or5.not();17List mockedList = Mockito.mock(List.class);18Mockito.when(mockedList.get(Mockito.argThat(multipleOf3))).thenReturn("Fizz");
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!!