cleanup work

This commit is contained in:
Eugen Paraschiv
2018-03-04 17:39:09 +02:00
parent 14bf9a24d5
commit d2a2a65566
193 changed files with 1504 additions and 2388 deletions
@@ -186,17 +186,12 @@ public class AsyncHttpClientTestCase {
WebSocket WEBSOCKET_CLIENT = null;
try {
WEBSOCKET_CLIENT = Dsl.asyncHttpClient()
.prepareGet("ws://localhost:5590/websocket")
.addHeader("header_name", "header_value")
.addQueryParam("key", "value")
.setRequestTimeout(5000)
.execute(wsHandler).get();
WEBSOCKET_CLIENT = Dsl.asyncHttpClient().prepareGet("ws://localhost:5590/websocket").addHeader("header_name", "header_value").addQueryParam("key", "value").setRequestTimeout(5000).execute(wsHandler).get();
if (WEBSOCKET_CLIENT.isOpen()) {
WEBSOCKET_CLIENT.sendPingFrame();
WEBSOCKET_CLIENT.sendTextFrame("test message");
WEBSOCKET_CLIENT.sendBinaryFrame(new byte[]{'t', 'e', 's', 't'});
WEBSOCKET_CLIENT.sendBinaryFrame(new byte[] { 't', 'e', 's', 't' });
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
@@ -35,10 +35,7 @@ public class AsyncServiceLongRunningUnitTest {
public void givenAsyncService_whenInitialize_thenInitOccurs2() {
asyncService.initialize();
Callable<Boolean> isInitialized = asyncService::isInitialized;
await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS)
.atMost(Duration.FIVE_SECONDS)
.with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS)
.until(isInitialized);
await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS).atMost(Duration.FIVE_SECONDS).with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(isInitialized);
}
@Test
@@ -60,9 +57,7 @@ public class AsyncServiceLongRunningUnitTest {
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs3() {
asyncService.initialize();
await().until(fieldIn(asyncService)
.ofType(boolean.class)
.andWithName("initialized"), equalTo(true));
await().until(fieldIn(asyncService).ofType(boolean.class).andWithName("initialized"), equalTo(true));
}
@Test
@@ -77,10 +72,6 @@ public class AsyncServiceLongRunningUnitTest {
@Test
public void givenAsyncService_whenGetValue_thenExceptionIgnored() {
asyncService.initialize();
given().ignoreException(IllegalStateException.class)
.await()
.atMost(Duration.FIVE_SECONDS)
.atLeast(Duration.FIVE_HUNDRED_MILLISECONDS)
.until(asyncService::getValue, equalTo(0L));
given().ignoreException(IllegalStateException.class).await().atMost(Duration.FIVE_SECONDS).atLeast(Duration.FIVE_HUNDRED_MILLISECONDS).until(asyncService::getValue, equalTo(0L));
}
}
@@ -28,14 +28,11 @@ public class BouncyCastleLiveTest {
char[] keyPassword = "password".toCharArray();
@Test
public void givenCryptographicResource_whenOperationSuccess_returnTrue()
throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException,
KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
public void givenCryptographicResource_whenOperationSuccess_returnTrue() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
Security.addProvider(new BouncyCastleProvider());
CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
X509Certificate certificate = (X509Certificate) certFactory
.generateCertificate(new FileInputStream(certificatePath));
X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new FileInputStream(certificatePath));
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(privateKeyPath), p12Password);
PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword);
@@ -21,14 +21,9 @@ public class ByteBuddyUnitTest {
@Test
public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException {
DynamicType.Unloaded unloadedType = new ByteBuddy()
.subclass(Object.class)
.method(ElementMatchers.isToString())
.intercept(FixedValue.value("Hello World ByteBuddy!"))
.make();
DynamicType.Unloaded unloadedType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.isToString()).intercept(FixedValue.value("Hello World ByteBuddy!")).make();
Class<?> dynamicType = unloadedType.load(getClass().getClassLoader())
.getLoaded();
Class<?> dynamicType = unloadedType.load(getClass().getClassLoader()).getLoaded();
assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
}
@@ -36,12 +31,7 @@ public class ByteBuddyUnitTest {
@Test
public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception {
ByteBuddyAgent.install();
new ByteBuddy()
.redefine(Foo.class)
.method(named("sayHelloFoo"))
.intercept(FixedValue.value("Hello Foo Redefined"))
.make()
.load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
new ByteBuddy().redefine(Foo.class).method(named("sayHelloFoo")).intercept(FixedValue.value("Hello Foo Redefined")).make().load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Foo f = new Foo();
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
}
@@ -49,34 +39,16 @@ public class ByteBuddyUnitTest {
@Test
public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException {
String r = new ByteBuddy()
.subclass(Foo.class)
.method(
named("sayHelloFoo")
.and(isDeclaredBy(Foo.class)
.and(returns(String.class)))
)
.intercept(MethodDelegation.to(Bar.class))
.make()
.load(getClass().getClassLoader())
.getLoaded()
.newInstance()
.sayHelloFoo();
String r = new ByteBuddy().subclass(Foo.class).method(named("sayHelloFoo").and(isDeclaredBy(Foo.class).and(returns(String.class)))).intercept(MethodDelegation.to(Bar.class)).make().load(getClass().getClassLoader()).getLoaded().newInstance()
.sayHelloFoo();
assertEquals(r, Bar.sayHelloBar());
}
@Test
public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception {
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.name("MyClassName")
.defineMethod("custom", String.class, Modifier.PUBLIC)
.intercept(MethodDelegation.to(Bar.class))
.defineField("x", String.class, Modifier.PUBLIC)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
Class<?> type = new ByteBuddy().subclass(Object.class).name("MyClassName").defineMethod("custom", String.class, Modifier.PUBLIC).intercept(MethodDelegation.to(Bar.class)).defineField("x", String.class, Modifier.PUBLIC).make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
Method m = type.getDeclaredMethod("custom", null);
@@ -85,5 +57,4 @@ public class ByteBuddyUnitTest {
}
}
@@ -16,10 +16,7 @@ public class CaffeineUnitTest {
@Test
public void givenCache_whenPopulate_thenValueStored() {
Cache<String, DataObject> cache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES)
.maximumSize(100)
.build();
Cache<String, DataObject> cache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(100).build();
String key = "A";
DataObject dataObject = cache.getIfPresent(key);
@@ -44,10 +41,7 @@ public class CaffeineUnitTest {
@Test
public void givenLoadingCache_whenGet_thenValuePopulated() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumSize(100)
.expireAfterWrite(1, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
String key = "A";
DataObject dataObject = cache.get(key);
@@ -63,10 +57,7 @@ public class CaffeineUnitTest {
@Test
public void givenAsyncLoadingCache_whenGet_thenValuePopulated() {
AsyncLoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumSize(100)
.expireAfterWrite(1, TimeUnit.MINUTES)
.buildAsync(k -> DataObject.get("Data for " + k));
AsyncLoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).buildAsync(k -> DataObject.get("Data for " + k));
String key = "A";
cache.get(key).thenAccept(dataObject -> {
@@ -74,16 +65,12 @@ public class CaffeineUnitTest {
assertEquals("Data for " + key, dataObject.getData());
});
cache.getAll(Arrays.asList("A", "B", "C"))
.thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
}
@Test
public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumSize(1)
.refreshAfterWrite(10, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(1).refreshAfterWrite(10, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
@@ -99,10 +86,7 @@ public class CaffeineUnitTest {
@Test
public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumWeight(10)
.weigher((k,v) -> 5)
.build(k -> DataObject.get("Data for " + k));
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumWeight(10).weigher((k, v) -> 5).build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
@@ -122,20 +106,11 @@ public class CaffeineUnitTest {
@Test
public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)
.weakKeys()
.weakValues()
.build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).weakKeys().weakValues().build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)
.softValues()
.build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).softValues().build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().expireAfter(new Expiry<String, DataObject>() {
@Override
@@ -154,17 +129,12 @@ public class CaffeineUnitTest {
}
}).build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder()
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
}
@Test
public void givenCache_whenStatsEnabled_thenStatsRecorded() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder()
.maximumSize(100)
.recordStats()
.build(k -> DataObject.get("Data for " + k));
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).recordStats().build(k -> DataObject.get("Data for " + k));
cache.get("A");
cache.get("A");
@@ -1,6 +1,5 @@
package com.baeldung.cglib.proxy;
import net.sf.cglib.beans.BeanGenerator;
import org.junit.Test;
@@ -12,21 +11,17 @@ public class BeanGeneratorIntegrationTest {
@Test
public void givenBeanCreator_whenAddProperty_thenClassShouldHaveFieldValue() throws Exception {
//given
// given
BeanGenerator beanGenerator = new BeanGenerator();
//when
// when
beanGenerator.addProperty("name", String.class);
Object myBean = beanGenerator.create();
Method setter = myBean
.getClass()
.getMethod("setName", String.class);
Method setter = myBean.getClass().getMethod("setName", String.class);
setter.invoke(myBean, "some string value set by a cglib");
//then
Method getter = myBean
.getClass()
.getMethod("getName");
// then
Method getter = myBean.getClass().getMethod("getName");
assertEquals("some string value set by a cglib", getter.invoke(myBean));
}
}
@@ -14,14 +14,11 @@ public class MixinUnitTest {
@Test
public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception {
//when
Mixin mixin = Mixin.create(
new Class[]{Interface1.class, Interface2.class, MixinInterface.class},
new Object[]{new Class1(), new Class2()}
);
// when
Mixin mixin = Mixin.create(new Class[] { Interface1.class, Interface2.class, MixinInterface.class }, new Object[] { new Class1(), new Class2() });
MixinInterface mixinDelegate = (MixinInterface) mixin;
//then
// then
assertEquals("first behaviour", mixinDelegate.first());
assertEquals("second behaviour", mixinDelegate.second());
}
@@ -10,34 +10,34 @@ import static org.junit.Assert.assertEquals;
public class ProxyIntegrationTest {
@Test
public void givenPersonService_whenSayHello_thenReturnResult() {
//given
// given
PersonService personService = new PersonService();
//when
// when
String res = personService.sayHello("Tom");
//then
// then
assertEquals(res, "Hello Tom");
}
@Test
public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod() throws Exception {
//given
// given
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((FixedValue) () -> "Hello Tom!");
PersonService proxy = (PersonService) enhancer.create();
//when
// when
String res = proxy.sayHello(null);
//then
// then
assertEquals("Hello Tom!", res);
}
@Test
public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod() throws Exception {
//given
// given
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
@@ -48,10 +48,10 @@ public class ProxyIntegrationTest {
}
});
//when
// when
PersonService proxy = (PersonService) enhancer.create();
//then
// then
assertEquals("Hello Tom!", proxy.sayHello(null));
int lengthOfName = proxy.lengthOfName("Mary");
assertEquals(4, lengthOfName);
@@ -14,12 +14,12 @@ import net.openhft.chronicle.ExcerptTailer;
import net.openhft.chronicle.tools.ChronicleTools;
public class ChronicleQueueIntegrationTest {
@Test
public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException {
File queueDir = Files.createTempDirectory("chronicle-queue").toFile();
ChronicleTools.deleteOnExit(queueDir.getPath());
Chronicle chronicle = ChronicleQueueBuilder.indexed(queueDir).build();
String stringVal = "Hello World";
int intVal = 101;
@@ -37,7 +37,7 @@ public class ChronicleQueueIntegrationTest {
}
tailer.finish();
tailer.close();
chronicle.close();
chronicle.close();
}
}
@@ -10,8 +10,7 @@ import org.junit.Test;
public class CourseServiceTest {
@Test
public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues()
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Course course = new Course();
String name = "Computer Science";
List<String> codes = Arrays.asList("CS", "CS01");
@@ -36,8 +35,7 @@ public class CourseServiceTest {
}
@Test
public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName()
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Course course = new Course();
course.setName("Computer Science");
course.setCodes(Arrays.asList("CS"));
@@ -1,6 +1,5 @@
package com.baeldung.commons.collections;
import com.baeldung.commons.collectionutil.Address;
import com.baeldung.commons.collectionutil.Customer;
import org.apache.commons.collections4.CollectionUtils;
@@ -21,7 +20,6 @@ import static org.junit.Assert.assertTrue;
public class CollectionUtilsGuideTest {
Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234");
Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567");
List<Customer> list1, list2, list3, linkedList1;
@@ -77,8 +75,8 @@ public class CollectionUtilsGuideTest {
}
});
//filterInverse does the opposite. It removes the element from the list if the Predicate returns true
//select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
// filterInverse does the opposite. It removes the element from the list if the Predicate returns true
// select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
assertTrue(isModified && linkedList1.size() == 2);
}
@@ -88,8 +86,8 @@ public class CollectionUtilsGuideTest {
List<Customer> emptyList = new ArrayList<>();
List<Customer> nullList = null;
//Very handy at times where we want to check if a collection is not null and not empty too.
//isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
// Very handy at times where we want to check if a collection is not null and not empty too.
// isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
assertTrue(CollectionUtils.isNotEmpty(list1));
assertTrue(CollectionUtils.isEmpty(nullList));
assertTrue(CollectionUtils.isEmpty(emptyList));
@@ -27,16 +27,8 @@ import static org.junit.Assert.assertTrue;
public class MapUtilsTest {
private String[][] color2DArray = new String[][]{
{"RED", "#FF0000"},
{"GREEN", "#00FF00"},
{"BLUE", "#0000FF"}
};
private String[] color1DArray = new String[]{
"RED", "#FF0000",
"GREEN", "#00FF00",
"BLUE", "#0000FF"
};
private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } };
private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" };
private Map<String, String> colorMap;
@Before
@@ -92,34 +84,26 @@ public class MapUtilsTest {
Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);
int size = invColorMap.size();
Assertions.assertThat(invColorMap)
.hasSameSizeAs(colorMap)
.containsKeys(this.colorMap.values().toArray(new String[size]))
.containsValues(this.colorMap.keySet().toArray(new String[size]));
Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size]));
}
@Test(expected = IllegalArgumentException.class)
public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() {
Map<String, String> rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(
new HashMap<String, String>(),
this.color1DArray));
Map<String, String> rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap<String, String>(), this.color1DArray));
rgbMap.put("ORANGE", "#FFA500");
}
@Test(expected = IllegalArgumentException.class)
public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() {
Map<String, String> uniqValuesMap
= MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
Map<String, String> uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
uniqValuesMap.put("NEW_RED", "#FF0000");
}
@Test
public void whenCreateLazyMap_theMapIsCreated() {
Map<Integer, String> intStrMap = MapUtils.lazyMap(
new HashMap<Integer, String>(),
TransformerUtils.stringValueTransformer());
Map<Integer, String> intStrMap = MapUtils.lazyMap(new HashMap<Integer, String>(), TransformerUtils.stringValueTransformer());
assertThat(intStrMap, is(anEmptyMap()));
@@ -17,8 +17,7 @@ public class SetUtilsUnitTest {
public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() {
Set<String> sourceSet = new HashSet<>();
sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1"));
Set<String> validatingSet
= SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L"));
Set<String> validatingSet = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L"));
validatingSet.add("Err Source2");
}
@@ -14,8 +14,8 @@ import static org.junit.Assert.assertEquals;
public class OrderedMapUnitTest {
private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"};
private Integer[] ages = {37, 28, 40, 36, 21};
private String[] names = { "Emily", "Mathew", "Rose", "John", "Anna" };
private Integer[] ages = { 37, 28, 40, 36, 21 };
private int RUNNERS_COUNT = names.length;
@@ -15,94 +15,88 @@ import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
public class BagTests {
@Test
public void givenMultipleCopies_whenAdded_theCountIsKept() {
Bag<Integer> bag = new HashBag<>(
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
assertThat(bag.getCount(1), equalTo(2));
}
@Test
public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() {
Collection<Integer> collection = new ArrayList<>();
// Collection contract defines that add() should return true
assertThat(collection.add(9), is(true));
// Even when element is already in the collection
collection.add(1);
assertThat(collection.add(1), is(true));
Bag<Integer> bag = new HashBag<>();
// Bag returns true on adding a new element
assertThat(bag.add(9), is(true));
bag.add(1);
// But breaks the contract with false when it has to increment the count
assertThat(bag.add(1), is(not(true)));
}
@Test
public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() {
Bag<Integer> bag = CollectionBag.collectionBag(new HashBag<>());
bag.add(1);
// This time the behavior is compliant to the Java Collection
assertThat(bag.add(1), is((true)));
}
@Test
public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() {
Bag<Integer> bag = new HashBag<>();
// Adding 1 for 5 times
bag.add(1, 5);
assertThat(bag.getCount(1), equalTo(5));
}
@Test
public void givenMultipleCopies_whenRemove_allAreRemoved() {
Bag<Integer> bag = new HashBag<>(
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
// From 3 we delete 1, 2 remain
bag.remove(3, 1);
assertThat(bag.getCount(3), equalTo(2));
// From 2 we delete all
bag.remove(1);
assertThat(bag.getCount(1), equalTo(0));
}
@Test
public void givenTree_whenDuplicateElementsAdded_thenSort() {
TreeBag<Integer> bag = new TreeBag<>(
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
TreeBag<Integer> bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
assertThat(bag.getCount(bag.last()), equalTo(3));
}
@Test
public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() {
SortedBag<Integer> bag = CollectionSortedBag
.collectionSortedBag(new TreeBag<>());
SortedBag<Integer> bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>());
bag.add(1);
assertThat(bag.add(1), is((true)));
}
@Test
public void givenSortedBag_whenDuplicateElementsAdded_thenSort() {
SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag
.synchronizedSortedBag(new TreeBag<>(
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
@@ -29,10 +29,7 @@ public class CSVReaderWriterTest {
@Test
public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException {
Reader in = new FileReader("src/test/resources/book.csv");
Iterable<CSVRecord> records = CSVFormat.DEFAULT
.withHeader(HEADERS)
.withFirstRecordAsHeader()
.parse(in);
Iterable<CSVRecord> records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in);
for (CSVRecord record : records) {
String author = record.get("author");
String title = record.get("title");
@@ -52,9 +49,7 @@ public class CSVReaderWriterTest {
}
});
}
assertEquals(EXPECTED_FILESTREAM, sw
.toString()
.trim());
assertEquals(EXPECTED_FILESTREAM, sw.toString().trim());
}
}
@@ -47,10 +47,8 @@ public class DbUtilsUnitTest {
List<Map<String, Object>> list = runner.query(connection, "SELECT * FROM employee", beanListHandler);
assertEquals(list.size(), 5);
assertEquals(list.get(0)
.get("firstname"), "John");
assertEquals(list.get(4)
.get("firstname"), "Christian");
assertEquals(list.get(0).get("firstname"), "John");
assertEquals(list.get(4).get("firstname"), "Christian");
}
@Test
@@ -61,10 +59,8 @@ public class DbUtilsUnitTest {
List<Employee> employeeList = runner.query(connection, "SELECT * FROM employee", beanListHandler);
assertEquals(employeeList.size(), 5);
assertEquals(employeeList.get(0)
.getFirstName(), "John");
assertEquals(employeeList.get(4)
.getFirstName(), "Christian");
assertEquals(employeeList.get(0).getFirstName(), "John");
assertEquals(employeeList.get(4).getFirstName(), "Christian");
}
@Test
@@ -85,12 +81,8 @@ public class DbUtilsUnitTest {
QueryRunner runner = new QueryRunner();
List<Employee> employees = runner.query(connection, "SELECT * FROM employee", employeeHandler);
assertEquals(employees.get(0)
.getEmails()
.size(), 2);
assertEquals(employees.get(2)
.getEmails()
.size(), 3);
assertEquals(employees.get(0).getEmails().size(), 2);
assertEquals(employees.get(2).getEmails().size(), 3);
assertNotNull(employees.get(0).getEmails().get(0).getEmployeeId());
}
@@ -25,30 +25,23 @@ import java.nio.charset.Charset;
public class CommonsIOUnitTest {
@Test
public void whenCopyANDReadFileTesttxt_thenMatchExpectedData()
throws IOException {
public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() throws IOException {
String expectedData = "Hello World from fileTest.txt!!!";
File file = FileUtils.getFile(getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath());
File file = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath());
File tempDir = FileUtils.getTempDirectory();
FileUtils.copyFileToDirectory(file, tempDir);
File newTempFile = FileUtils.getFile(tempDir, file.getName());
String data = FileUtils.readFileToString(newTempFile,
Charset.defaultCharset());
String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());
Assert.assertEquals(expectedData, data.trim());
}
@Test
public void whenUsingFileNameUtils_thenshowdifferentFileOperations()
throws IOException {
public void whenUsingFileNameUtils_thenshowdifferentFileOperations() throws IOException {
String path = getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath();
String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
String fullPath = FilenameUtils.getFullPath(path);
String extension = FilenameUtils.getExtension(path);
@@ -60,70 +53,54 @@ public class CommonsIOUnitTest {
}
@Test
public void whenUsingFileSystemUtils_thenDriveFreeSpace()
throws IOException {
public void whenUsingFileSystemUtils_thenDriveFreeSpace() throws IOException {
long freeSpace = FileSystemUtils.freeSpaceKb("/");
}
@SuppressWarnings("resource")
@Test
public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams()
throws IOException {
public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() throws IOException {
final String str = "Hello World.";
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1,outputStream2);
FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]);
Assert.assertEquals(str, String.valueOf(outputStream1));
Assert.assertEquals(str, String.valueOf(outputStream2));
}
}
@Test
public void whenGetFilewithNameFileFilter_thenFindfileTesttxt()
throws IOException {
public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() throws IOException {
final String testFile = "fileTest.txt";
String path = getClass().getClassLoader()
.getResource(testFile)
.getPath();
String path = getClass().getClassLoader().getResource(testFile).getPath();
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
String[] possibleNames = { "NotThisOne", testFile };
Assert.assertEquals(testFile,
dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]);
Assert.assertEquals(testFile, dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]);
}
@Test
public void whenGetFilewith_ANDFileFilter_thenFindsampletxt()
throws IOException {
public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() throws IOException {
String path = getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath();
String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
Assert.assertEquals("sample.txt",
dir.list(new AndFileFilter(
new WildcardFileFilter("*ple*", IOCase.INSENSITIVE),
new SuffixFileFilter("txt")))[0]);
Assert.assertEquals("sample.txt", dir.list(new AndFileFilter(new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), new SuffixFileFilter("txt")))[0]);
}
@Test
public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt()
throws IOException {
public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() throws IOException {
PathFileComparator pathFileComparator = new PathFileComparator(
IOCase.INSENSITIVE);
String path = FilenameUtils.getFullPath(getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath());
PathFileComparator pathFileComparator = new PathFileComparator(IOCase.INSENSITIVE);
String path = FilenameUtils.getFullPath(getClass().getClassLoader().getResource("fileTest.txt").getPath());
File dir = new File(path);
File[] files = dir.listFiles();
@@ -133,16 +110,11 @@ public class CommonsIOUnitTest {
}
@Test
public void whenSizeFileComparator_thenLargerFile()
throws IOException {
public void whenSizeFileComparator_thenLargerFile() throws IOException {
SizeFileComparator sizeFileComparator = new SizeFileComparator();
File largerFile = FileUtils.getFile(getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath());
File smallerFile = FileUtils.getFile(getClass().getClassLoader()
.getResource("sample.txt")
.getPath());
File largerFile = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath());
File smallerFile = FileUtils.getFile(getClass().getClassLoader().getResource("sample.txt").getPath());
int i = sizeFileComparator.compare(largerFile, smallerFile);
@@ -9,71 +9,71 @@ import static org.junit.Assert.assertEquals;
public class ArrayUtilsUnitTest {
@Test
public void givenArray_whenAddingElementAtSpecifiedPosition_thenCorrect() {
int[] oldArray = {2, 3, 4, 5};
int[] oldArray = { 2, 3, 4, 5 };
int[] newArray = ArrayUtils.add(oldArray, 0, 1);
int[] expectedArray = {1, 2, 3, 4, 5};
int[] expectedArray = { 1, 2, 3, 4, 5 };
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenAddingElementAtTheEnd_thenCorrect() {
int[] oldArray = {2, 3, 4, 5};
int[] oldArray = { 2, 3, 4, 5 };
int[] newArray = ArrayUtils.add(oldArray, 1);
int[] expectedArray = {2, 3, 4, 5, 1};
int[] expectedArray = { 2, 3, 4, 5, 1 };
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() {
int[] oldArray = {0, 1, 2};
int[] oldArray = { 0, 1, 2 };
int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5);
int[] expectedArray = {0, 1, 2, 3, 4, 5};
int[] expectedArray = { 0, 1, 2, 3, 4, 5 };
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingElementAtSpecifiedPosition_thenCorrect() {
int[] oldArray = {1, 2, 3, 4, 5};
int[] oldArray = { 1, 2, 3, 4, 5 };
int[] newArray = ArrayUtils.remove(oldArray, 1);
int[] expectedArray = {1, 3, 4, 5};
int[] expectedArray = { 1, 3, 4, 5 };
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingAllElementsAtSpecifiedPositions_thenCorrect() {
int[] oldArray = {1, 2, 3, 4, 5};
int[] oldArray = { 1, 2, 3, 4, 5 };
int[] newArray = ArrayUtils.removeAll(oldArray, 1, 3);
int[] expectedArray = {1, 3, 5};
int[] expectedArray = { 1, 3, 5 };
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingAnElement_thenCorrect() {
int[] oldArray = {1, 2, 3, 3, 4};
int[] oldArray = { 1, 2, 3, 3, 4 };
int[] newArray = ArrayUtils.removeElement(oldArray, 3);
int[] expectedArray = {1, 2, 3, 4};
int[] expectedArray = { 1, 2, 3, 4 };
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingElements_thenCorrect() {
int[] oldArray = {1, 2, 3, 3, 4};
int[] oldArray = { 1, 2, 3, 3, 4 };
int[] newArray = ArrayUtils.removeElements(oldArray, 2, 3, 5);
int[] expectedArray = {1, 3, 4};
int[] expectedArray = { 1, 3, 4 };
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenRemovingAllElementOccurences_thenCorrect() {
int[] oldArray = {1, 2, 2, 2, 3};
int[] oldArray = { 1, 2, 2, 2, 3 };
int[] newArray = ArrayUtils.removeAllOccurences(oldArray, 2);
int[] expectedArray = {1, 3};
int[] expectedArray = { 1, 3 };
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenCheckingExistingElement_thenCorrect() {
int[] array = {1, 3, 5, 7, 9};
int[] array = { 1, 3, 5, 7, 9 };
boolean evenContained = ArrayUtils.contains(array, 2);
boolean oddContained = ArrayUtils.contains(array, 7);
assertEquals(false, evenContained);
@@ -82,57 +82,57 @@ public class ArrayUtilsUnitTest {
@Test
public void givenArray_whenReversingElementsWithinARange_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5};
int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(originalArray, 1, 4);
int[] expectedArray = {1, 4, 3, 2, 5};
int[] expectedArray = { 1, 4, 3, 2, 5 };
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenReversingAllElements_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5};
int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(originalArray);
int[] expectedArray = {5, 4, 3, 2, 1};
int[] expectedArray = { 5, 4, 3, 2, 1 };
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenShiftingElementsWithinARange_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5};
int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.shift(originalArray, 1, 4, 1);
int[] expectedArray = {1, 4, 2, 3, 5};
int[] expectedArray = { 1, 4, 2, 3, 5 };
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenShiftingAllElements_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5};
int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.shift(originalArray, 1);
int[] expectedArray = {5, 1, 2, 3, 4};
int[] expectedArray = { 5, 1, 2, 3, 4 };
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenExtractingElements_thenCorrect() {
int[] oldArray = {1, 2, 3, 4, 5};
int[] oldArray = { 1, 2, 3, 4, 5 };
int[] newArray = ArrayUtils.subarray(oldArray, 2, 7);
int[] expectedArray = {3, 4, 5};
int[] expectedArray = { 3, 4, 5 };
assertArrayEquals(expectedArray, newArray);
}
@Test
public void givenArray_whenSwapingElementsWithinARange_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5};
int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.swap(originalArray, 0, 3, 2);
int[] expectedArray = {4, 5, 3, 1, 2};
int[] expectedArray = { 4, 5, 3, 1, 2 };
assertArrayEquals(expectedArray, originalArray);
}
@Test
public void givenArray_whenSwapingElementsAtSpecifiedPositions_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5};
int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.swap(originalArray, 0, 3);
int[] expectedArray = {4, 2, 3, 1, 5};
int[] expectedArray = { 4, 2, 3, 1, 5 };
assertArrayEquals(expectedArray, originalArray);
}
}
@@ -15,7 +15,7 @@ public class IntegrationTest {
final double i = integrator.integrate(100, function, 0, 10);
Assert.assertEquals(16 + 2d/3d, i, 1e-7);
Assert.assertEquals(16 + 2d / 3d, i, 1e-7);
}
}
@@ -8,9 +8,7 @@ public class LinearAlgebraUnitTest {
@Test
public void whenDecompositionSolverSolve_thenCorrect() {
RealMatrix a =
new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } },
false);
RealMatrix a = new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } }, false);
RealVector b = new ArrayRealVector(new double[] { 1, -2, 1 }, false);
DecompositionSolver solver = new LUDecomposition(a).getSolver();
@@ -12,10 +12,10 @@ public class StatisticsUnitTest {
@Before
public void setUp() {
values = new double[] {65, 51 , 16, 11 , 6519, 191 ,0 , 98, 19854, 1, 32};
values = new double[] { 65, 51, 16, 11, 6519, 191, 0, 98, 19854, 1, 32 };
descriptiveStatistics = new DescriptiveStatistics();
for(double v : values) {
for (double v : values) {
descriptiveStatistics.addValue(v);
}
}
@@ -13,42 +13,41 @@ public class CRDTTest {
@Test
public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() {
//given
// given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
final GSet<String> replica1 = crdtStore1.createGSet("ID_1");
final GSet<String> replica2 = crdtStore2.<String>findGSet("ID_1").get();
final GSet<String> replica2 = crdtStore2.<String> findGSet("ID_1").get();
//when
// when
replica1.add("apple");
replica2.add("banana");
//then
// then
assertThat(replica1).contains("apple", "banana");
assertThat(replica2).contains("apple", "banana");
//when
// when
crdtStore1.disconnect(crdtStore2);
replica1.add("strawberry");
replica2.add("pear");
assertThat(replica1).contains("apple", "banana", "strawberry");
assertThat(replica2).contains("apple", "banana", "pear");
crdtStore1.connect(crdtStore2);
//then
// then
assertThat(replica1).contains("apple", "banana", "strawberry", "pear");
assertThat(replica2).contains("apple", "banana", "strawberry", "pear");
}
@Test
public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() {
//given
// given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2);
@@ -56,21 +55,20 @@ public class CRDTTest {
final GCounter replica1 = crdtStore1.createGCounter("ID_1");
final GCounter replica2 = crdtStore2.findGCounter("ID_1").get();
//when
// when
replica1.increment();
replica2.increment(2L);
//then
// then
assertThat(replica1.get()).isEqualTo(3L);
assertThat(replica2.get()).isEqualTo(3L);
//when
// when
crdtStore1.disconnect(crdtStore2);
replica1.increment(3L);
replica2.increment(5L);
assertThat(replica1.get()).isEqualTo(6L);
assertThat(replica2.get()).isEqualTo(8L);
@@ -91,15 +89,15 @@ public class CRDTTest {
final PNCounter replica1 = crdtStore1.createPNCounter("ID_1");
final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get();
//when
// when
replica1.increment();
replica2.decrement(2L);
//then
// then
assertThat(replica1.get()).isEqualTo(-1L);
assertThat(replica2.get()).isEqualTo(-1L);
//when
// when
crdtStore1.disconnect(crdtStore2);
replica1.decrement(3L);
@@ -110,22 +108,22 @@ public class CRDTTest {
crdtStore1.connect(crdtStore2);
//then
// then
assertThat(replica1.get()).isEqualTo(1L);
assertThat(replica2.get()).isEqualTo(1L);
}
@Test
public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() {
//given
// given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1");
final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2");
crdtStore1.connect(crdtStore2);
final LWWRegister<String> replica1 = crdtStore1.createLWWRegister("ID_1");
final LWWRegister<String> replica2 = crdtStore2.<String>findLWWRegister("ID_1").get();
final LWWRegister<String> replica2 = crdtStore2.<String> findLWWRegister("ID_1").get();
//when
// when
replica1.set("apple");
replica2.set("banana");
@@ -133,20 +131,18 @@ public class CRDTTest {
assertThat(replica1.get()).isEqualTo("banana");
assertThat(replica2.get()).isEqualTo("banana");
// when
crdtStore1.disconnect(crdtStore2);
replica1.set("strawberry");
replica2.set("pear");
assertThat(replica1.get()).isEqualTo("strawberry");
assertThat(replica2.get()).isEqualTo("pear");
crdtStore1.connect(crdtStore2);
//then
// then
assertThat(replica1.get()).isEqualTo("pear");
assertThat(replica2.get()).isEqualTo("pear");
}
@@ -19,25 +19,19 @@ public class DistinctWithJavaFunctionUnitTest {
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = personList.stream()
.filter(distinctByKey(p -> p.getName()))
.collect(Collectors.toList());
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getName())).collect(Collectors.toList());
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = personList.stream()
.filter(distinctByKey(p -> p.getAge()))
.collect(Collectors.toList());
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getAge())).collect(Collectors.toList());
assertTrue(personListFiltered.size() == 2);
}
@Test
public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() {
List<Person> personListFiltered = personList.stream()
.distinct()
.collect(Collectors.toList());
List<Person> personListFiltered = personList.stream().distinct().collect(Collectors.toList());
assertTrue(personListFiltered.size() == 5);
}
@@ -19,17 +19,13 @@ public class DistinctWithStreamexUnitTest {
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = StreamEx.of(personList)
.distinct(Person::getName)
.toList();
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getName).toList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = StreamEx.of(personList)
.distinct(Person::getAge)
.toList();
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getAge).toList();
assertTrue(personListFiltered.size() == 2);
}
@@ -17,17 +17,13 @@ public class DistinctWithVavrUnitTest {
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList)
.distinctBy(Person::getName)
.toJavaList();
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getName).toJavaList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList)
.distinctBy(Person::getAge)
.toJavaList();
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getAge).toJavaList();
assertTrue(personListFiltered.size() == 2);
}
@@ -27,138 +27,96 @@ public class ContainerLiveTest {
@Test
public void whenListingRunningContainers_thenReturnNonEmptyList() {
//when
// when
List<Container> containers = dockerClient.listContainersCmd().exec();
//then
// then
assertThat(containers.size(), is(not(0)));
}
@Test
public void whenListingExitedContainers_thenReturnNonEmptyList() {
//when
List<Container> containers = dockerClient.listContainersCmd()
.withShowSize(true)
.withShowAll(true)
.withStatusFilter("exited")
.exec();
// when
List<Container> containers = dockerClient.listContainersCmd().withShowSize(true).withShowAll(true).withStatusFilter("exited").exec();
//then
// then
assertThat(containers.size(), is(not(0)));
}
@Test
public void whenCreatingContainer_thenMustReturnContainerId() {
//when
CreateContainerResponse container
= dockerClient.createContainerCmd("mongo:3.6")
.withCmd("--bind_ip_all")
.withName("mongo")
.withHostName("baeldung")
.withEnv("MONGO_LATEST_VERSION=3.6")
.withPortBindings(PortBinding.parse("9999:27017"))
.exec();
// when
CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6").withCmd("--bind_ip_all").withName("mongo").withHostName("baeldung").withEnv("MONGO_LATEST_VERSION=3.6").withPortBindings(PortBinding.parse("9999:27017")).exec();
//then
// then
assertThat(container.getId(), is(not(null)));
}
@Test
public void whenHavingContainer_thenRunContainer() throws InterruptedException {
//when
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
// when
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
Thread.sleep(3000);
//then
dockerClient.startContainerCmd(container.getId())
.exec();
// then
dockerClient.startContainerCmd(container.getId()).exec();
dockerClient.stopContainerCmd(container.getId())
.exec();
dockerClient.stopContainerCmd(container.getId()).exec();
}
@Test
public void whenRunningContainer_thenStopContainer() throws InterruptedException {
//when
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
// when
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
Thread.sleep(3000);
dockerClient.startContainerCmd(container.getId())
.exec();
dockerClient.startContainerCmd(container.getId()).exec();
//then
dockerClient.stopContainerCmd(container.getId())
.exec();
// then
dockerClient.stopContainerCmd(container.getId()).exec();
}
@Test
public void whenRunningContainer_thenKillContainer() throws InterruptedException {
//when
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
// when
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
dockerClient.startContainerCmd(container.getId())
.exec();
dockerClient.startContainerCmd(container.getId()).exec();
Thread.sleep(3000);
dockerClient.stopContainerCmd(container.getId())
.exec();
dockerClient.stopContainerCmd(container.getId()).exec();
//then
dockerClient.killContainerCmd(container.getId())
.exec();
// then
dockerClient.killContainerCmd(container.getId()).exec();
}
@Test
public void whenHavingContainer_thenInspectContainer() {
//when
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
// when
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
//then
InspectContainerResponse containerResponse
= dockerClient.inspectContainerCmd(container.getId())
.exec();
// then
InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(container.getId()).exec();
assertThat(containerResponse.getId(), is(container.getId()));
}
@Test
public void givenContainer_whenCommittingContainer_thenMustReturnImageId() {
//given
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
// given
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
//when
String imageId = dockerClient.commitCmd(container.getId())
.withEnv("SNAPSHOT_YEAR=2018")
.withMessage("add git support")
.withCmd("sleep", "10000")
.withRepository("alpine")
.withTag("3.6.v2").exec();
// when
String imageId = dockerClient.commitCmd(container.getId()).withEnv("SNAPSHOT_YEAR=2018").withMessage("add git support").withCmd("sleep", "10000").withRepository("alpine").withTag("3.6.v2").exec();
//then
// then
assertThat(imageId, is(not(null)));
}
@@ -14,52 +14,40 @@ public class DockerClientLiveTest {
@Test
public void whenCreatingDockerClient_thenReturnDefaultInstance() {
//when
DefaultDockerClientConfig.Builder config
= DefaultDockerClientConfig.createDefaultConfigBuilder();
// when
DefaultDockerClientConfig.Builder config = DefaultDockerClientConfig.createDefaultConfigBuilder();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
//then
// then
assertNotNull(dockerClient);
}
@Test
public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() {
//when
DockerClient dockerClient
= DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375")
.build();
// when
DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375").build();
//then
// then
assertNotNull(dockerClient);
}
@Test
public void whenCreatingAdvanceDockerClient_thenReturnInstance() {
//when
DefaultDockerClientConfig config
= DefaultDockerClientConfig.createDefaultConfigBuilder()
.withRegistryEmail("info@bealdung.com")
.withRegistryUrl("register.bealdung.io/v2/")
.withRegistryPassword("strongpassword")
.withRegistryUsername("bealdung")
.withDockerCertPath("/home/bealdung/public/.docker/certs")
.withDockerConfig("/home/bealdung/public/.docker/")
.withDockerTlsVerify("1")
.withDockerHost("tcp://docker.beauldung.com:2376")
.build();
// when
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withRegistryEmail("info@bealdung.com").withRegistryUrl("register.bealdung.io/v2/").withRegistryPassword("strongpassword").withRegistryUsername("bealdung")
.withDockerCertPath("/home/bealdung/public/.docker/certs").withDockerConfig("/home/bealdung/public/.docker/").withDockerTlsVerify("1").withDockerHost("tcp://docker.beauldung.com:2376").build();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
//then
// then
assertNotNull(dockerClient);
}
@Test
public void whenCreatingDockerClientWithProperties_thenReturnInstance() {
//when
// when
Properties properties = new Properties();
properties.setProperty("registry.email", "info@bealdung.com");
properties.setProperty("registry.url", "register.bealdung.io/v2/");
@@ -70,14 +58,11 @@ public class DockerClientLiveTest {
properties.setProperty("DOCKER_TLS_VERIFY", "1");
properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376");
DefaultDockerClientConfig config
= DefaultDockerClientConfig.createDefaultConfigBuilder()
.withProperties(properties)
.build();
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withProperties(properties).build();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
//then
// then
assertNotNull(dockerClient);
}
}
@@ -33,99 +33,84 @@ public class ImageLiveTest {
@Test
public void whenListingImages_thenReturnNonEmptyList() {
//when
// when
List<Image> images = dockerClient.listImagesCmd().exec();
//then
// then
assertThat(images.size(), is(not(0)));
}
@Test
public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() {
//when
List<Image> images = dockerClient.listImagesCmd()
.withShowAll(true).exec();
// when
List<Image> images = dockerClient.listImagesCmd().withShowAll(true).exec();
//then
// then
assertThat(images.size(), is(not(0)));
}
@Test
public void whenListingDanglingImages_thenReturnNonNullList() {
//when
List<Image> images = dockerClient.listImagesCmd()
.withDanglingFilter(true).exec();
// when
List<Image> images = dockerClient.listImagesCmd().withDanglingFilter(true).exec();
//then
// then
assertThat(images, is(not(null)));
}
@Test
public void whenBuildingImage_thenMustReturnImageId() {
//when
String imageId = dockerClient.buildImageCmd()
.withDockerfile(new File("src/test/resources/dockerapi/Dockerfile"))
.withPull(true)
.withNoCache(true)
.withTag("alpine:git")
.exec(new BuildImageResultCallback())
.awaitImageId();
// when
String imageId = dockerClient.buildImageCmd().withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")).withPull(true).withNoCache(true).withTag("alpine:git").exec(new BuildImageResultCallback()).awaitImageId();
//then
// then
assertThat(imageId, is(not(null)));
}
@Test
public void givenListOfImages_whenInspectImage_thenMustReturnObject() {
//given
// given
List<Image> images = dockerClient.listImagesCmd().exec();
Image image = images.get(0);
//when
InspectImageResponse imageResponse
= dockerClient.inspectImageCmd(image.getId()).exec();
// when
InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec();
//then
// then
assertThat(imageResponse.getId(), is(image.getId()));
}
@Test
public void givenListOfImages_whenTagImage_thenListMustIncrement() {
//given
// given
List<Image> images = dockerClient.listImagesCmd().exec();
Image image = images.get(0);
//when
// when
dockerClient.tagImageCmd(image.getId(), "baeldung/alpine", "3.6.v2").exec();
//then
// then
List<Image> imagesNow = dockerClient.listImagesCmd().exec();
assertThat(imagesNow.size(), is(greaterThan(images.size())));
}
public void pushingAnImage() throws InterruptedException {
dockerClient.pushImageCmd("baeldung/alpine")
.withTag("3.6.v2")
.exec(new PushImageResultCallback())
.awaitCompletion(90, TimeUnit.SECONDS);
dockerClient.pushImageCmd("baeldung/alpine").withTag("3.6.v2").exec(new PushImageResultCallback()).awaitCompletion(90, TimeUnit.SECONDS);
}
@Test
public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException {
//when
dockerClient.pullImageCmd("alpine")
.withTag("latest")
.exec(new PullImageResultCallback())
.awaitCompletion(30, TimeUnit.SECONDS);
// when
dockerClient.pullImageCmd("alpine").withTag("latest").exec(new PullImageResultCallback()).awaitCompletion(30, TimeUnit.SECONDS);
//then
// then
List<Image> images = dockerClient.listImagesCmd().exec();
assertThat(images.size(), is(not(0)));
}
@@ -133,12 +118,12 @@ public class ImageLiveTest {
@Test
public void whenRemovingImage_thenImageListDecrease() {
//when
// when
List<Image> images = dockerClient.listImagesCmd().exec();
Image image = images.get(0);
dockerClient.removeImageCmd(image.getId()).exec();
//then
// then
List<Image> imagesNow = dockerClient.listImagesCmd().exec();
assertThat(imagesNow.size(), is(lessThan(images.size())));
}
@@ -146,10 +131,10 @@ public class ImageLiveTest {
@Test
public void whenSearchingImage_thenMustReturn25Items() {
//when
// when
List<SearchItem> items = dockerClient.searchImagesCmd("Java").exec();
//then
// then
assertThat(items.size(), is(25));
}
}
@@ -27,64 +27,51 @@ public class NetworkLiveTest {
@Test
public void whenListingNetworks_thenSizeMustBeGreaterThanZero() {
//when
// when
List<Network> networks = dockerClient.listNetworksCmd().exec();
//then
// then
assertThat(networks.size(), is(greaterThan(0)));
}
@Test
public void whenCreatingNetwork_thenRetrieveResponse() {
//when
CreateNetworkResponse networkResponse
= dockerClient.createNetworkCmd()
.withName("baeldungDefault")
.withDriver("bridge").exec();
// when
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec();
//then
// then
assertThat(networkResponse, is(not(null)));
}
@Test
public void whenCreatingAdvanceNetwork_thenRetrieveResponse() {
//when
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd()
.withName("baeldungAdvanced")
.withIpam(new Ipam()
.withConfig(new Ipam.Config()
.withSubnet("172.36.0.0/16")
.withIpRange("172.36.5.0/24")))
.withDriver("bridge").exec();
// when
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungAdvanced").withIpam(new Ipam().withConfig(new Ipam.Config().withSubnet("172.36.0.0/16").withIpRange("172.36.5.0/24"))).withDriver("bridge").exec();
//then
// then
assertThat(networkResponse, is(not(null)));
}
@Test
public void whenInspectingNetwork_thenSizeMustBeGreaterThanZero() {
//when
// when
String networkName = "bridge";
Network network
= dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
Network network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
//then
// then
assertThat(network.getName(), is(networkName));
}
@Test
public void whenCreatingNetwork_thenRemove() throws InterruptedException {
//when
CreateNetworkResponse networkResponse
= dockerClient.createNetworkCmd()
.withName("baeldungDefault")
.withDriver("bridge").exec();
// when
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec();
//then
// then
Thread.sleep(4000);
dockerClient.removeNetworkCmd(networkResponse.getId()).exec();
}
@@ -27,10 +27,10 @@ public class VolumeLiveTest {
@Test
public void whenListingVolumes_thenSizeMustBeGreaterThanZero() {
//when
// when
ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
//then
// then
List<InspectVolumeResponse> volumes = volumesResponse.getVolumes();
assertThat(volumes.size(), is(greaterThan(0)));
}
@@ -38,48 +38,45 @@ public class VolumeLiveTest {
@Test
public void givenVolumes_whenInspectingVolume_thenReturnNonNullResponse() {
//given
// given
ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
List<InspectVolumeResponse> volumes = volumesResponse.getVolumes();
InspectVolumeResponse volume = volumes.get(0);
//when
InspectVolumeResponse volumeResponse
= dockerClient.inspectVolumeCmd(volume.getName()).exec();
// when
InspectVolumeResponse volumeResponse = dockerClient.inspectVolumeCmd(volume.getName()).exec();
//then
// then
assertThat(volumeResponse, is(not(null)));
}
@Test
public void whenCreatingUnnamedVolume_thenGetVolumeId() {
//when
// when
CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec();
//then
// then
assertThat(unnamedVolume.getName(), is(not(null)));
}
@Test
public void whenCreatingNamedVolume_thenGetVolumeId() {
//when
CreateVolumeResponse namedVolume
= dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
// when
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
//then
// then
assertThat(namedVolume.getName(), is(not(null)));
}
@Test
public void whenGettingNamedVolume_thenRemove() throws InterruptedException {
//when
CreateVolumeResponse namedVolume
= dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec();
// when
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec();
//then
// then
Thread.sleep(4000);
dockerClient.removeVolumeCmd(namedVolume.getName()).exec();
}
@@ -17,7 +17,6 @@ public class CollectPatternTest {
MutableList<String> lastNames = students.collect(Student::getLastName);
Assertions.assertThat(lastNames)
.containsExactly("Hopkins", "Adams");
Assertions.assertThat(lastNames).containsExactly("Hopkins", "Adams");
}
}
@@ -12,7 +12,6 @@ public class ConvertContainerToAnotherTest {
public void whenConvertContainerToAnother_thenCorrect() {
MutableList<String> cars = (MutableList) ConvertContainerToAnother.convertToList();
Assertions.assertThat(cars)
.containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes"));
Assertions.assertThat(cars).containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes"));
}
}
@@ -20,7 +20,6 @@ public class DetectPatternTest {
public void whenDetect_thenCorrect() {
Integer result = list.detect(Predicates.greaterThan(30));
Assertions.assertThat(result)
.isEqualTo(41);
Assertions.assertThat(result).isEqualTo(41);
}
}
@@ -44,7 +44,6 @@ public class FlatCollectTest {
public void whenFlatCollect_thenCorrect() {
MutableList<String> addresses = students.flatCollect(Student::getAddresses);
Assertions.assertThat(addresses)
.containsExactlyElementsOf(this.expectedAddresses);
Assertions.assertThat(addresses).containsExactlyElementsOf(this.expectedAddresses);
}
}
@@ -17,7 +17,7 @@ public class InjectIntoPatternTest {
Integer v = list.get(i);
result = result + v.intValue();
}
assertEquals(15, result);
}
}
@@ -18,7 +18,6 @@ public class LazyIterationTest {
LazyIterable<Student> lazyStudents = students.asLazy();
LazyIterable<String> lastNames = lazyStudents.collect(Student::getLastName);
Assertions.assertThat(lastNames)
.containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez"));
Assertions.assertThat(lastNames).containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez"));
}
}
@@ -31,14 +31,10 @@ public class PartitionPatternTest {
return each > 30;
}
});
MutableList<Integer> greaterThanThirty = partitionedFolks.getSelected()
.sortThis();
MutableList<Integer> smallerThanThirty = partitionedFolks.getRejected()
.sortThis();
MutableList<Integer> greaterThanThirty = partitionedFolks.getSelected().sortThis();
MutableList<Integer> smallerThanThirty = partitionedFolks.getRejected().sortThis();
Assertions.assertThat(smallerThanThirty)
.containsExactly(1, 5, 8, 17, 23);
Assertions.assertThat(greaterThanThirty)
.containsExactly(31, 38, 41);
Assertions.assertThat(smallerThanThirty).containsExactly(1, 5, 8, 17, 23);
Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
}
@@ -20,10 +20,8 @@ public class RejectPatternTest {
@Test
public void whenReject_thenCorrect() {
MutableList<Integer> notGreaterThanThirty = list.reject(Predicates.greaterThan(30))
.sortThis();
MutableList<Integer> notGreaterThanThirty = list.reject(Predicates.greaterThan(30)).sortThis();
Assertions.assertThat(notGreaterThanThirty)
.containsExactlyElementsOf(this.expectedList);
Assertions.assertThat(notGreaterThanThirty).containsExactlyElementsOf(this.expectedList);
}
}
@@ -18,17 +18,14 @@ public class SelectPatternTest {
@Test
public void givenListwhenSelect_thenCorrect() {
MutableList<Integer> greaterThanThirty = list.select(Predicates.greaterThan(30))
.sortThis();
MutableList<Integer> greaterThanThirty = list.select(Predicates.greaterThan(30)).sortThis();
Assertions.assertThat(greaterThanThirty)
.containsExactly(31, 38, 41);
Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
@SuppressWarnings("rawtypes")
public MutableList selectUsingLambda() {
return list.select(each -> each > 30)
.sortThis();
return list.select(each -> each > 30).sortThis();
}
@SuppressWarnings("unchecked")
@@ -36,7 +33,6 @@ public class SelectPatternTest {
public void givenListwhenSelectUsingLambda_thenCorrect() {
MutableList<Integer> greaterThanThirty = selectUsingLambda();
Assertions.assertThat(greaterThanThirty)
.containsExactly(31, 38, 41);
Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
}
@@ -28,7 +28,6 @@ public class ZipTest {
MutableList<String> cars = Lists.mutable.with("Porsche", "Volvo", "Toyota");
MutableList<Pair<String, String>> pairs = numbers.zip(cars);
Assertions.assertThat(pairs)
.containsExactlyElementsOf(this.expectedPairs);
Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs);
}
}
@@ -27,7 +27,6 @@ public class ZipWithIndexTest {
MutableList<String> cars = FastList.newListWith("Porsche", "Volvo", "Toyota");
MutableList<Pair<String, Integer>> pairs = cars.zipWithIndex();
Assertions.assertThat(pairs)
.containsExactlyElementsOf(this.expectedPairs);
Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs);
}
}
@@ -12,49 +12,49 @@ import fj.function.Characters;
import fj.function.Integers;
public class FunctionalJavaTest {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
@Test
public void calculateEvenNumbers_givenIntList_returnTrue() {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
List<Boolean> evenListTrueResult = List.list(false, true, false, true);
List<Boolean> evenListFalseResult = List.list(true, false, false, true);
assertEquals(evenList.equals(evenListTrueResult), true);
assertEquals(evenList.equals(evenListFalseResult), false);
}
@Test
public void mapList_givenIntList_returnResult() {
List<Integer> fList = List.list(3, 4, 5, 6);
fList = fList.map(i -> i + 100);
List<Integer> resultList = List.list(103, 104, 105, 106);
List<Integer> falseResultList = List.list(15, 504, 105, 106);
assertEquals(fList.equals(resultList), true);
assertEquals(fList.equals(falseResultList), false);
List<Integer> fList = List.list(3, 4, 5, 6);
fList = fList.map(i -> i + 100);
List<Integer> resultList = List.list(103, 104, 105, 106);
List<Integer> falseResultList = List.list(15, 504, 105, 106);
assertEquals(fList.equals(resultList), true);
assertEquals(fList.equals(falseResultList), false);
}
@Test
public void filterList_givenIntList_returnResult() {
Array<Integer> array = Array.array(3, 4, 5, 6);
Array<Integer> filteredArray = array.filter(Integers.even);
Array<Integer> result = Array.array(4, 6);
Array<Integer> wrongResult = Array.array(3, 5);
assertEquals(filteredArray.equals(result), true);
assertEquals(filteredArray.equals(wrongResult), false);
Array<Integer> array = Array.array(3, 4, 5, 6);
Array<Integer> filteredArray = array.filter(Integers.even);
Array<Integer> result = Array.array(4, 6);
Array<Integer> wrongResult = Array.array(3, 5);
assertEquals(filteredArray.equals(result), true);
assertEquals(filteredArray.equals(wrongResult), false);
}
@Test
public void checkForLowerCase_givenStringArray_returnResult() {
Array<String> array = Array.array("Welcome", "To", "baeldung");
Array<String> array2 = Array.array("Welcome", "To", "Baeldung");
Array<String> array = Array.array("Welcome", "To", "baeldung");
Array<String> array2 = Array.array("Welcome", "To", "Baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
assertEquals(isExist, true);
assertEquals(isExist2, false);
}
@Test
public void checkOptions_givenOptions_returnResult() {
Option<Integer> n1 = Option.some(1);
@@ -64,16 +64,16 @@ public class FunctionalJavaTest {
Option<Integer> result1 = n1.bind(f1);
Option<Integer> result2 = n2.bind(f1);
assertEquals(result1, Option.none());
assertEquals(result2, Option.some(102));
}
@Test
public void foldLeft_givenArray_returnResult() {
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
assertEquals(sum, 260);
}
}
@@ -20,51 +20,45 @@ import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class WordCountIntegrationTest {
private final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
@Test
public void givenDataSet_whenExecuteWordCount_thenReturnWordCount() throws Exception {
//given
// given
List<String> lines = Arrays.asList("This is a first sentence", "This is a second sentence with a one word");
//when
// when
DataSet<Tuple2<String, Integer>> result = WordCount.startWordCount(env, lines);
//then
// then
List<Tuple2<String, Integer>> collect = result.collect();
assertThat(collect).containsExactlyInAnyOrder(
new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1),
new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1),
new Tuple2<>("first", 1), new Tuple2<>("with", 1), new Tuple2<>("one", 1));
assertThat(collect).containsExactlyInAnyOrder(new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1), new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1), new Tuple2<>("first", 1), new Tuple2<>("with", 1),
new Tuple2<>("one", 1));
}
@Test
public void givenListOfAmounts_whenUseMapReduce_thenSumAmountsThatAreOnlyAboveThreshold() throws Exception {
//given
// given
DataSet<Integer> amounts = env.fromElements(1, 29, 40, 50);
int threshold = 30;
//when
List<Integer> collect = amounts
.filter(a -> a > threshold)
.reduce((integer, t1) -> integer + t1)
.collect();
// when
List<Integer> collect = amounts.filter(a -> a > threshold).reduce((integer, t1) -> integer + t1).collect();
//then
// then
assertThat(collect.get(0)).isEqualTo(90);
}
@Test
public void givenDataSetOfComplexObjects_whenMapToGetOneField_thenReturnedListHaveProperElements() throws Exception {
//given
// given
DataSet<Person> personDataSource = env.fromCollection(Arrays.asList(new Person(23, "Tom"), new Person(75, "Michael")));
//when
// when
List<Integer> ages = personDataSource.map(p -> p.age).collect();
//then
// then
assertThat(ages).hasSize(2);
assertThat(ages).contains(23, 75);
@@ -72,44 +66,33 @@ public class WordCountIntegrationTest {
@Test
public void givenDataSet_whenSortItByOneField_thenShouldReturnSortedDataSet() throws Exception {
//given
// given
Tuple2<Integer, String> secondPerson = new Tuple2<>(4, "Tom");
Tuple2<Integer, String> thirdPerson = new Tuple2<>(5, "Scott");
Tuple2<Integer, String> fourthPerson = new Tuple2<>(200, "Michael");
Tuple2<Integer, String> firstPerson = new Tuple2<>(1, "Jack");
DataSet<Tuple2<Integer, String>> transactions = env.fromElements(fourthPerson, secondPerson,
thirdPerson, firstPerson);
DataSet<Tuple2<Integer, String>> transactions = env.fromElements(fourthPerson, secondPerson, thirdPerson, firstPerson);
// when
List<Tuple2<Integer, String>> sorted = transactions.sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING).collect();
//when
List<Tuple2<Integer, String>> sorted = transactions
.sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING)
.collect();
//then
// then
assertThat(sorted).containsExactly(firstPerson, secondPerson, thirdPerson, fourthPerson);
}
@Test
public void giveTwoDataSets_whenJoinUsingId_thenProduceJoinedData() throws Exception {
//given
// given
Tuple3<Integer, String, String> address = new Tuple3<>(1, "5th Avenue", "London");
DataSet<Tuple3<Integer, String, String>> addresses = env.fromElements(address);
Tuple2<Integer, String> firstTransaction = new Tuple2<>(1, "Transaction_1");
DataSet<Tuple2<Integer, String>> transactions =
env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2"));
DataSet<Tuple2<Integer, String>> transactions = env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2"));
// when
List<Tuple2<Tuple2<Integer, String>, Tuple3<Integer, String, String>>> joined = transactions.join(addresses).where(new IdKeySelectorTransaction()).equalTo(new IdKeySelectorAddress()).collect();
//when
List<Tuple2<Tuple2<Integer, String>, Tuple3<Integer, String, String>>> joined =
transactions.join(addresses)
.where(new IdKeySelectorTransaction())
.equalTo(new IdKeySelectorAddress())
.collect();
//then
// then
assertThat(joined).hasSize(1);
assertThat(joined).contains(new Tuple2<>(firstTransaction, address));
@@ -117,48 +100,40 @@ public class WordCountIntegrationTest {
@Test
public void givenStreamOfEvents_whenProcessEvents_thenShouldPrintResultsOnSinkOperation() throws Exception {
//given
// given
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<String> text
= env.fromElements("This is a first sentence", "This is a second sentence with a one word");
DataStream<String> text = env.fromElements("This is a first sentence", "This is a second sentence with a one word");
SingleOutputStreamOperator<String> upperCase = text.map(String::toUpperCase);
upperCase.print();
//when
// when
env.execute();
}
@Test
public void givenStreamOfEvents_whenProcessEvents_thenShouldApplyWindowingOnTransformation() throws Exception {
//given
// given
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
SingleOutputStreamOperator<Tuple2<Integer, Long>> windowed = env.fromElements(
new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()),
new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond())
).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple2<Integer, Long>>(Time.seconds(20)) {
@Override
public long extractTimestamp(Tuple2<Integer, Long> element) {
return element.f1 * 1000;
}
});
SingleOutputStreamOperator<Tuple2<Integer, Long>> windowed = env.fromElements(new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()), new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond()))
.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple2<Integer, Long>>(Time.seconds(20)) {
@Override
public long extractTimestamp(Tuple2<Integer, Long> element) {
return element.f1 * 1000;
}
});
SingleOutputStreamOperator<Tuple2<Integer, Long>> reduced = windowed
.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
.maxBy(0, true);
SingleOutputStreamOperator<Tuple2<Integer, Long>> reduced = windowed.windowAll(TumblingEventTimeWindows.of(Time.seconds(5))).maxBy(0, true);
reduced.print();
//when
// when
env.execute();
}
private static class IdKeySelectorTransaction implements KeySelector<Tuple2<Integer, String>, Integer> {
@Override
public Integer getKey(Tuple2<Integer, String> value) {
@@ -30,7 +30,7 @@ public class GoogleSheetsIntegrationTest {
private static Sheets sheetsService;
// this id can be replaced with your spreadsheet id
// this id can be replaced with your spreadsheet id
// otherwise be advised that multiple people may run this test and update the public spreadsheet
private static final String SPREADSHEET_ID = "1sILuxZUnyl_7-MlNThjt765oWshN3Xs-PPLfqYe4DhI";
@@ -41,100 +41,56 @@ public class GoogleSheetsIntegrationTest {
@Test
public void whenWriteSheet_thenReadSheetOk() throws IOException {
ValueRange body = new ValueRange()
.setValues(Arrays.asList(
Arrays.asList("Expenses January"),
Arrays.asList("books", "30"),
Arrays.asList("pens", "10"),
Arrays.asList("Expenses February"),
Arrays.asList("clothes", "20"),
Arrays.asList("shoes", "5")));
UpdateValuesResponse result = sheetsService.spreadsheets().values()
.update(SPREADSHEET_ID, "A1", body)
.setValueInputOption("RAW")
.execute();
List<ValueRange> data = new ArrayList<>();
data.add(new ValueRange()
.setRange("D1")
.setValues(Arrays.asList(
Arrays.asList("January Total", "=B2+B3"))));
data.add(new ValueRange()
.setRange("D4")
.setValues(Arrays.asList(
Arrays.asList("February Total", "=B5+B6"))));
ValueRange body = new ValueRange().setValues(Arrays.asList(Arrays.asList("Expenses January"), Arrays.asList("books", "30"), Arrays.asList("pens", "10"), Arrays.asList("Expenses February"), Arrays.asList("clothes", "20"), Arrays.asList("shoes", "5")));
UpdateValuesResponse result = sheetsService.spreadsheets().values().update(SPREADSHEET_ID, "A1", body).setValueInputOption("RAW").execute();
List<ValueRange> data = new ArrayList<>();
data.add(new ValueRange().setRange("D1").setValues(Arrays.asList(Arrays.asList("January Total", "=B2+B3"))));
data.add(new ValueRange().setRange("D4").setValues(Arrays.asList(Arrays.asList("February Total", "=B5+B6"))));
BatchUpdateValuesRequest batchBody = new BatchUpdateValuesRequest().setValueInputOption("USER_ENTERED").setData(data);
BatchUpdateValuesResponse batchResult = sheetsService.spreadsheets().values().batchUpdate(SPREADSHEET_ID, batchBody).execute();
List<String> ranges = Arrays.asList("E1", "E4");
BatchGetValuesResponse readResult = sheetsService.spreadsheets().values().batchGet(SPREADSHEET_ID).setRanges(ranges).execute();
BatchUpdateValuesRequest batchBody = new BatchUpdateValuesRequest()
.setValueInputOption("USER_ENTERED")
.setData(data);
BatchUpdateValuesResponse batchResult =
sheetsService.spreadsheets().values()
.batchUpdate(SPREADSHEET_ID, batchBody)
.execute();
List<String> ranges = Arrays.asList("E1","E4");
BatchGetValuesResponse readResult =
sheetsService.spreadsheets().values()
.batchGet(SPREADSHEET_ID)
.setRanges(ranges)
.execute();
ValueRange januaryTotal = readResult.getValueRanges().get(0);
assertThat(januaryTotal.getValues().get(0).get(0)).isEqualTo("40");
ValueRange febTotal = readResult.getValueRanges().get(1);
assertThat(febTotal.getValues().get(0).get(0)).isEqualTo("25");
ValueRange appendBody = new ValueRange()
.setValues(Arrays.asList(
Arrays.asList("Total", "=E1+E4")));
AppendValuesResponse appendResult =
sheetsService.spreadsheets().values()
.append(SPREADSHEET_ID, "A1", appendBody)
.setValueInputOption("USER_ENTERED")
.setInsertDataOption("INSERT_ROWS")
.setIncludeValuesInResponse(true)
.execute();
ValueRange appendBody = new ValueRange().setValues(Arrays.asList(Arrays.asList("Total", "=E1+E4")));
AppendValuesResponse appendResult = sheetsService.spreadsheets().values().append(SPREADSHEET_ID, "A1", appendBody).setValueInputOption("USER_ENTERED").setInsertDataOption("INSERT_ROWS").setIncludeValuesInResponse(true).execute();
ValueRange total = appendResult.getUpdates().getUpdatedData();
assertThat(total.getValues().get(0).get(1)).isEqualTo("65");
}
@Test
public void whenUpdateSpreadSheetTitle_thenOk() throws IOException {
UpdateSpreadsheetPropertiesRequest updateRequest = new UpdateSpreadsheetPropertiesRequest()
.setFields("*")
.setProperties(new SpreadsheetProperties().setTitle("Expenses"));
CopyPasteRequest copyRequest = new CopyPasteRequest()
.setSource(new GridRange().setSheetId(0)
.setStartColumnIndex(0).setEndColumnIndex(2)
.setStartRowIndex(0).setEndRowIndex(1))
.setDestination(new GridRange().setSheetId(1)
.setStartColumnIndex(0).setEndColumnIndex(2)
.setStartRowIndex(0).setEndRowIndex(1))
.setPasteType("PASTE_VALUES");
UpdateSpreadsheetPropertiesRequest updateRequest = new UpdateSpreadsheetPropertiesRequest().setFields("*").setProperties(new SpreadsheetProperties().setTitle("Expenses"));
CopyPasteRequest copyRequest = new CopyPasteRequest().setSource(new GridRange().setSheetId(0).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1))
.setDestination(new GridRange().setSheetId(1).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)).setPasteType("PASTE_VALUES");
List<Request> requests = new ArrayList<>();
requests.add(new Request().setCopyPaste(copyRequest));
requests.add(new Request().setUpdateSpreadsheetProperties(updateRequest));
BatchUpdateSpreadsheetRequest body =
new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);
sheetsService.spreadsheets().batchUpdate(SPREADSHEET_ID, body).execute();
}
@Test
public void whenCreateSpreadSheet_thenIdOk() throws IOException {
Spreadsheet spreadSheet = new Spreadsheet()
.setProperties(new SpreadsheetProperties().setTitle("My Spreadsheet"));
Spreadsheet spreadSheet = new Spreadsheet().setProperties(new SpreadsheetProperties().setTitle("My Spreadsheet"));
Spreadsheet result = sheetsService.spreadsheets().create(spreadSheet).execute();
assertThat(result.getSpreadsheetId()).isNotNull();
assertThat(result.getSpreadsheetId()).isNotNull();
}
}
@@ -1,6 +1,5 @@
package com.baeldung.hll;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import net.agkn.hll.HLL;
@@ -15,47 +14,44 @@ public class HLLLongRunningUnitTest {
@Test
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {
//given
// given
long numberOfElements = 100_000_000;
long toleratedDifference = 1_000_000;
HashFunction hashFunction = Hashing.murmur3_128();
HLL hll = new HLL(14, 5);
//when
// when
LongStream.range(0, numberOfElements).forEach(element -> {
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
hll.addRaw(hashedValue);
}
);
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
hll.addRaw(hashedValue);
});
//then
// then
long cardinality = hll.cardinality();
assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference));
}
@Test
public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() {
//given
// given
long numberOfElements = 100_000_000;
long toleratedDifference = 1_000_000;
HashFunction hashFunction = Hashing.murmur3_128();
HLL firstHll = new HLL(15, 5);
HLL secondHLL = new HLL(15, 5);
//when
// when
LongStream.range(0, numberOfElements).forEach(element -> {
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
firstHll.addRaw(hashedValue);
}
);
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
firstHll.addRaw(hashedValue);
});
LongStream.range(numberOfElements, numberOfElements * 2).forEach(element -> {
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
secondHLL.addRaw(hashedValue);
}
);
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
secondHLL.addRaw(hashedValue);
});
//then
// then
firstHll.union(secondHLL);
long cardinality = firstHll.cardinality();
assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2));
@@ -33,38 +33,21 @@ import io.specto.hoverfly.junit.rule.HoverflyRule;
public class HoverflyApiIntegrationTest {
private static final SimulationSource source = dsl(
service("http://www.baeldung.com")
.get("/api/courses/1")
.willReturn(success().body(
jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))
.post("/api/courses")
.willReturn(success())
.andDelay(3, TimeUnit.SECONDS)
.forMethod("POST"),
service(matches("www.*dung.com"))
.get(startsWith("/api/student"))
.queryParam("page", any())
.willReturn(success())
.post(equalsTo("/api/student"))
.body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}")))
.willReturn(success())
.put("/api/student/1")
.body(matchesJsonPath("$.name"))
.willReturn(success())
.post("/api/student")
.body(equalsToXml("<student><id>2</id><name>John</name></student>"))
.willReturn(success())
.put("/api/student/2")
.body(matchesXPath("/student/name"))
.willReturn(success()));
private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))
.post("/api/courses").willReturn(success())
.andDelay(3, TimeUnit.SECONDS).forMethod("POST"),
service(matches("www.*dung.com")).get(startsWith("/api/student")).queryParam("page", any()).willReturn(success())
.post(equalsTo("/api/student")).body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))).willReturn(success())
.put("/api/student/1").body(matchesJsonPath("$.name")).willReturn(success())
.post("/api/student").body(equalsToXml("<student><id>2</id><name>John</name></student>")).willReturn(success())
.put("/api/student/2").body(matchesXPath("/student/name")).willReturn(success()));
@ClassRule
public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source);
@@ -72,19 +55,17 @@ public class HoverflyApiIntegrationTest {
@Test
public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<String> courseResponse = restTemplate.getForEntity(
"http://www.baeldung.com/api/courses/1", String.class);
final ResponseEntity<String> courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/courses/1", String.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody());
}
@Test
public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
final ResponseEntity<Void> postResponse = restTemplate.postForEntity(
"http://www.baeldung.com/api/courses", null, Void.class);
final ResponseEntity<Void> postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/courses", null, Void.class);
stopWatch.stop();
long postTime = stopWatch.getTime();
@@ -94,45 +75,36 @@ public class HoverflyApiIntegrationTest {
@Test
public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<Void> courseResponse = restTemplate.getForEntity(
"http://www.baeldung.com/api/student?page=3", Void.class);
final ResponseEntity<Void> courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/student?page=3", Void.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity(
"http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class);
final ResponseEntity<Void> postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity
.put(new URI("http://www.baeldung.com/api/student/1"))
.body("{\"id\":\"1\",\"name\":\"Trevor\"}");
RequestEntity<String> putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/1")).body("{\"id\":\"1\",\"name\":\"Trevor\"}");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity(
"http://www.baeldung.com/api/student", "<student><id>2</id><name>John</name></student>", Void.class);
final ResponseEntity<Void> postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "<student><id>2</id><name>John</name></student>", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity
.put(new URI("http://www.baeldung.com/api/student/2"))
.body("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<student><id>2</id><name>Monica</name></student>");
RequestEntity<String> putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/2")).body("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<student><id>2</id><name>Monica</name></student>");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
@@ -27,24 +27,17 @@ public class ConfigurationTest {
cacheManager = configuration.cacheManager();
Cache<String, Integer> transactionalCache =
configuration.transactionalCache(cacheManager, listener);
Cache<String, Integer> transactionalCache = configuration.transactionalCache(cacheManager, listener);
Cache<String, String> simpleHelloWorldCache =
configuration.simpleHelloWorldCache(cacheManager, listener);
Cache<String, String> simpleHelloWorldCache = configuration.simpleHelloWorldCache(cacheManager, listener);
Cache<String, String> expiringHelloWorldCache =
configuration.expiringHelloWorldCache(cacheManager, listener);
Cache<String, String> expiringHelloWorldCache = configuration.expiringHelloWorldCache(cacheManager, listener);
Cache<String, String> evictingHelloWorldCache =
configuration.evictingHelloWorldCache(cacheManager, listener);
Cache<String, String> evictingHelloWorldCache = configuration.evictingHelloWorldCache(cacheManager, listener);
Cache<String, String> passivatingHelloWorldCache =
configuration.passivatingHelloWorldCache(cacheManager, listener);
Cache<String, String> passivatingHelloWorldCache = configuration.passivatingHelloWorldCache(cacheManager, listener);
this.helloWorldService = new HelloWorldService(repository,
listener, simpleHelloWorldCache, expiringHelloWorldCache, evictingHelloWorldCache,
passivatingHelloWorldCache);
this.helloWorldService = new HelloWorldService(repository, listener, simpleHelloWorldCache, expiringHelloWorldCache, evictingHelloWorldCache, passivatingHelloWorldCache);
this.transactionalService = new TransactionalService(transactionalCache);
}
@@ -12,59 +12,46 @@ public class HelloWorldServiceUnitTest extends ConfigurationTest {
@Test
public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() {
assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld()))
.isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld()))
.isLessThan(100);
assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isLessThan(100);
}
@Test
public void whenGetIsCalledTwoTimesQuickly_thenTheSecondShouldHitTheCache() {
assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld()))
.isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld()))
.isLessThan(100);
assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isLessThan(100);
}
@Test
public void whenGetIsCalledTwoTimesSparsely_thenNeitherShouldHitTheCache()
throws InterruptedException {
public void whenGetIsCalledTwoTimesSparsely_thenNeitherShouldHitTheCache() throws InterruptedException {
assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld()))
.isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000);
Thread.sleep(1100);
assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld()))
.isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000);
}
@Test
public void givenOneEntryIsConfigured_whenTwoAreAdded_thenFirstShouldntBeAvailable() {
assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1")))
.isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 2")))
.isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1")))
.isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000);
}
@Test
public void givenOneEntryIsConfigured_whenTwoAreAdded_thenTheFirstShouldBeAvailable() {
assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1")))
.isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 2")))
.isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000);
assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1")))
.isLessThan(100);
assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isLessThan(100);
}
@@ -13,10 +13,9 @@ public class TransactionalServiceUnitTest extends ConfigurationTest {
Thread backgroundThread = new Thread(backGroundJob);
transactionalService.getQuickHowManyVisits();
backgroundThread.start();
Thread.sleep(100); //lets wait our thread warm up
Thread.sleep(100); // lets wait our thread warm up
assertThat(timeThis(() -> transactionalService.getQuickHowManyVisits()))
.isGreaterThan(500).isLessThan(1000);
assertThat(timeThis(() -> transactionalService.getQuickHowManyVisits())).isGreaterThan(500).isLessThan(1000);
}
}
@@ -1,6 +1,5 @@
package com.baeldung.jasypt;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.util.password.BasicPasswordEncryptor;
@@ -17,16 +16,16 @@ public class JasyptUnitTest {
@Test
public void givenTextPrivateData_whenDecrypt_thenCompareToEncrypted() {
//given
// given
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
String privateData = "secret-data";
textEncryptor.setPasswordCharArray("some-random-data".toCharArray());
//when
// when
String myEncryptedText = textEncryptor.encrypt(privateData);
assertNotSame(privateData, myEncryptedText); //myEncryptedText can be save in db
assertNotSame(privateData, myEncryptedText); // myEncryptedText can be save in db
//then
// then
String plainText = textEncryptor.decrypt(myEncryptedText);
assertEquals(plainText, privateData);
}
@@ -37,10 +36,10 @@ public class JasyptUnitTest {
BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
String encryptedPassword = passwordEncryptor.encryptPassword(password);
//when
// when
boolean result = passwordEncryptor.checkPassword("secret-pass", encryptedPassword);
//then
// then
assertTrue(result);
}
@@ -50,28 +49,27 @@ public class JasyptUnitTest {
BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
String encryptedPassword = passwordEncryptor.encryptPassword(password);
//when
// when
boolean result = passwordEncryptor.checkPassword("secret-pass-not-same", encryptedPassword);
//then
// then
assertFalse(result);
}
@Test
@Ignore("should have installed local_policy.jar")
public void givenTextPrivateData_whenDecrypt_thenCompareToEncryptedWithCustomAlgorithm() {
//given
// given
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
String privateData = "secret-data";
encryptor.setPassword("some-random-data");
encryptor.setAlgorithm("PBEWithMD5AndTripleDES");
//when
// when
String encryptedText = encryptor.encrypt("secret-pass");
assertNotSame(privateData, encryptedText);
//then
// then
String plainText = encryptor.decrypt(encryptedText);
assertEquals(plainText, privateData);
}
@@ -79,18 +77,18 @@ public class JasyptUnitTest {
@Test
@Ignore("should have installed local_policy.jar")
public void givenTextPrivateData_whenDecryptOnHighPerformance_thenDecrypt() {
//given
// given
String privateData = "secret-data";
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
encryptor.setPoolSize(4);
encryptor.setPassword("some-random-data");
encryptor.setAlgorithm("PBEWithMD5AndTripleDES");
//when
// when
String encryptedText = encryptor.encrypt(privateData);
assertNotSame(privateData, encryptedText);
//then
// then
String plainText = encryptor.decrypt(encryptedText);
assertEquals(plainText, privateData);
}
@@ -110,10 +110,7 @@ public class JavaDirectoryDeleteUnitTest {
public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
Files.walk(pathToBeDeleted).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@@ -1,6 +1,5 @@
package com.baeldung.javassist;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.NotFoundException;
@@ -33,20 +32,20 @@ import static org.junit.Assert.assertTrue;
public class JavasisstUnitTest {
@Test
public void givenJavasisstAPI_whenConstructClass_thenGenerateAClassFile() throws CannotCompileException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
//given
// given
String classNameWithPackage = "com.baeldung.JavassistGeneratedClass";
ClassFile cf = new ClassFile(false, classNameWithPackage, null);
cf.setInterfaces(new String[]{"java.lang.Cloneable"});
cf.setInterfaces(new String[] { "java.lang.Cloneable" });
FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I");
f.setAccessFlags(AccessFlag.PUBLIC);
cf.addField(f);
//when
// when
String className = "JavassistGeneratedClass.class";
cf.write(new DataOutputStream(new FileOutputStream(className)));
//then
// then
ClassPool classPool = ClassPool.getDefault();
Field[] fields = classPool.makeClass(cf).toClass().getFields();
assertEquals(fields[0].getName(), "id");
@@ -57,14 +56,14 @@ public class JavasisstUnitTest {
@Test
public void givenJavaClass_whenLoadAtByJavassist_thenTraversWholeClass() throws NotFoundException, CannotCompileException, BadBytecode {
//given
// given
ClassPool cp = ClassPool.getDefault();
ClassFile cf = cp.get("com.baeldung.javasisst.Point").getClassFile();
MethodInfo minfo = cf.getMethod("move");
CodeAttribute ca = minfo.getCodeAttribute();
CodeIterator ci = ca.iterator();
//when
// when
List<String> operations = new LinkedList<>();
while (ci.hasNext()) {
int index = ci.next();
@@ -72,23 +71,21 @@ public class JavasisstUnitTest {
operations.add(Mnemonic.OPCODE[op]);
}
//then
assertEquals(operations,
Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return"));
// then
assertEquals(operations, Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return"));
}
@Test
public void givenTableOfInstructions_whenAddNewInstruction_thenShouldConstructProperSequence() throws NotFoundException, BadBytecode, CannotCompileException, IllegalAccessException, InstantiationException {
//given
// given
ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.ThreeDimensionalPoint").getClassFile();
//when
// when
FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I");
f.setAccessFlags(AccessFlag.PUBLIC);
cf.addField(f);
ClassPool classPool = ClassPool.getDefault();
Field[] fields = classPool.makeClass(cf).toClass().getFields();
List<String> fieldsList = Stream.of(fields).map(Field::getName).collect(Collectors.toList());
@@ -98,19 +95,19 @@ public class JavasisstUnitTest {
@Test
public void givenLoadedClass_whenAddConstructorToClass_shouldCreateClassWithConstructor() throws NotFoundException, CannotCompileException, BadBytecode {
//given
// given
ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.Point").getClassFile();
Bytecode code = new Bytecode(cf.getConstPool());
code.addAload(0);
code.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V");
code.addReturn(null);
//when
// when
MethodInfo minfo = new MethodInfo(cf.getConstPool(), MethodInfo.nameInit, "()V");
minfo.setCodeAttribute(code.toCodeAttribute());
cf.addMethod(minfo);
//then
// then
CodeIterator ci = code.toCodeAttribute().iterator();
List<String> operations = new LinkedList<>();
while (ci.hasNext()) {
@@ -119,9 +116,7 @@ public class JavasisstUnitTest {
operations.add(Mnemonic.OPCODE[op]);
}
assertEquals(operations,
Arrays.asList("aload_0", "invokespecial", "return"));
assertEquals(operations, Arrays.asList("aload_0", "invokespecial", "return"));
}
}
@@ -26,7 +26,7 @@ public class JavaTuplesUnitTest {
Pair<String, String> pairFromList = Pair.fromIterable(collectionOfNames, 2);
String[] names = new String[]{"john", "doe", "anne"};
String[] names = new String[] { "john", "doe", "anne" };
Triplet<String, String, String> triplet2 = Triplet.fromArray(names);
}
@@ -1,6 +1,5 @@
package com.baeldung.javers;
import org.javers.common.collections.Lists;
import org.javers.core.Javers;
import org.javers.core.JaversBuilder;
@@ -21,16 +20,16 @@ public class JaversUnitTest {
@Test
public void givenPersonObject_whenApplyModificationOnIt_thenShouldDetectChange() {
//given
// given
Javers javers = JaversBuilder.javers().build();
Person person = new Person(1, "Michael Program");
Person personAfterModification = new Person(1, "Michael Java");
//when
// when
Diff diff = javers.compare(person, personAfterModification);
//then
// then
ValueChange change = diff.getChangesByType(ValueChange.class).get(0);
assertThat(diff.getChanges()).hasSize(1);
@@ -39,22 +38,20 @@ public class JaversUnitTest {
assertThat(change.getRight()).isEqualTo("Michael Java");
}
@Test
public void givenListOfPersons_whenCompare_ThenShouldDetectChanges() {
//given
// given
Javers javers = JaversBuilder.javers().build();
Person personThatWillBeRemoved = new Person(2, "Thomas Link");
List<Person> oldList = Lists.asList(new Person(1, "Michael Program"), personThatWillBeRemoved);
List<Person> newList = Lists.asList(new Person(1, "Michael Not Program"));
//when
// when
Diff diff = javers.compareCollections(oldList, newList, Person.class);
//then
// then
assertThat(diff.getChanges()).hasSize(3);
ValueChange valueChange = diff.getChangesByType(ValueChange.class).get(0);
assertThat(valueChange.getPropertyName()).isEqualTo("name");
assertThat(valueChange.getLeft()).isEqualTo("Michael Program");
@@ -70,43 +67,36 @@ public class JaversUnitTest {
@Test
public void givenListOfPerson_whenPersonHasNewAddress_thenDetectThatChange() {
//given
// given
Javers javers = JaversBuilder.javers().build();
PersonWithAddress person =
new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
PersonWithAddress personWithNewAddress =
new PersonWithAddress(1, "Tom",
Arrays.asList(new Address("England"), new Address("USA")));
PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"), new Address("USA")));
//when
// when
Diff diff = javers.compare(person, personWithNewAddress);
List objectsByChangeType = diff.getObjectsByChangeType(NewObject.class);
//then
// then
assertThat(objectsByChangeType).hasSize(1);
assertThat(objectsByChangeType.get(0).equals(new Address("USA")));
}
@Test
public void givenListOfPerson_whenPersonRemovedAddress_thenDetectThatChange() {
//given
// given
Javers javers = JaversBuilder.javers().build();
PersonWithAddress person =
new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
PersonWithAddress personWithNewAddress =
new PersonWithAddress(1, "Tom", Collections.emptyList());
PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Collections.emptyList());
//when
// when
Diff diff = javers.compare(person, personWithNewAddress);
List objectsByChangeType = diff.getObjectsByChangeType(ObjectRemoved.class);
//then
// then
assertThat(objectsByChangeType).hasSize(1);
assertThat(objectsByChangeType.get(0).equals(new Address("England")));
}
@@ -23,15 +23,13 @@ public class CacheLoaderTest {
public void setup() {
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<Integer, String> config = new MutableConfiguration<Integer, String>().setReadThrough(true)
.setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader()));
MutableConfiguration<Integer, String> config = new MutableConfiguration<Integer, String>().setReadThrough(true).setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader()));
this.cache = cacheManager.createCache("SimpleCache", config);
}
@After
public void tearDown() {
Caching.getCachingProvider()
.getCacheManager().destroyCache(CACHE_NAME);
Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME);
}
@Test
@@ -29,8 +29,7 @@ public class EntryProcessorTest {
@After
public void tearDown() {
Caching.getCachingProvider()
.getCacheManager().destroyCache(CACHE_NAME);
Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME);
}
@Test
@@ -33,14 +33,12 @@ public class EventListenerTest {
@After
public void tearDown() {
Caching.getCachingProvider()
.getCacheManager().destroyCache(CACHE_NAME);
Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME);
}
@Test
public void whenRunEvent_thenCorrect() throws InterruptedException {
this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder
.factoryOf(this.listener), null, false, true);
this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder.factoryOf(this.listener), null, false, true);
this.cache.registerCacheEntryListener(this.listenerConfiguration);
assertEquals(false, this.listener.getCreated());
@@ -10,7 +10,7 @@ import javax.cache.spi.CachingProvider;
import static org.junit.Assert.assertEquals;
public class JCacheTest {
public class JCacheIntegrationTest {
@Test
public void instantiateCache() {
@@ -106,5 +106,4 @@ public class GuideToJDOIntegrationTest {
}
}
}
@@ -1,6 +1,5 @@
package com.baeldung.jetty;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
@@ -32,26 +31,26 @@ public class JettyIntegrationTest {
@Test
public void givenServer_whenSendRequestToBlockingServlet_thenReturnStatusOK() throws Exception {
//given
// given
String url = "http://localhost:8090/status";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
//then
// then
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
}
@Test
public void givenServer_whenSendRequestToNonBlockingServlet_thenReturnStatusOK() throws Exception {
//when
// when
String url = "http://localhost:8090/heavy/async";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
//then
// then
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
String responseContent = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
assertThat(responseContent).isEqualTo("This is some heavy resource that will be served in an async way");
@@ -18,69 +18,69 @@ import org.junit.Test;
*/
public class JettyServerFactoryUnitTest {
/**
* Tests that when a base server is provided a request returns a status 404.
*
* @throws Exception
*/
@Test
public void givenBaseServer_whenHttpRequest_thenStatus404() throws Exception {
Server server = JettyServerFactory.createBaseServer();
server.start();
int statusCode = sendGetRequest();
Assert.assertEquals(404, statusCode);
server.stop();
}
/**
* Tests that when a base server is provided a request returns a status 404.
*
* @throws Exception
*/
@Test
public void givenBaseServer_whenHttpRequest_thenStatus404() throws Exception {
Server server = JettyServerFactory.createBaseServer();
server.start();
/**
* Tests that when a web app server is provided a request returns a status
* 200.
*
* @throws Exception
*/
@Test
public void givenWebAppServer_whenHttpRequest_thenStatus200() throws Exception {
Server server = JettyServerFactory.createWebAppServer();
server.start();
int statusCode = sendGetRequest();
int statusCode = sendGetRequest();
Assert.assertEquals(200, statusCode);
server.stop();
}
Assert.assertEquals(404, statusCode);
server.stop();
}
/**
* Tests that when a multi handler server is provided a request returns a
* status 200.
*
* @throws Exception
*/
@Test
public void givenMultiHandlerServerServer_whenHttpRequest_thenStatus200() throws Exception {
Server server = JettyServerFactory.createMultiHandlerServer();
server.start();
/**
* Tests that when a web app server is provided a request returns a status
* 200.
*
* @throws Exception
*/
@Test
public void givenWebAppServer_whenHttpRequest_thenStatus200() throws Exception {
Server server = JettyServerFactory.createWebAppServer();
server.start();
int statusCode = sendGetRequest();
Assert.assertEquals(200, statusCode);
server.stop();
}
int statusCode = sendGetRequest();
/**
* Sends a default HTTP GET request to the server and returns the response
* status code.
*
* @return the status code of the response
* @throws Exception
*/
private int sendGetRequest() throws Exception {
HttpHost target = new HttpHost("localhost", JettyServerFactory.SERVER_PORT);
HttpRequest request = new HttpGet(JettyServerFactory.APP_PATH);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(target, request);
return response.getStatusLine().getStatusCode();
}
Assert.assertEquals(200, statusCode);
server.stop();
}
/**
* Tests that when a multi handler server is provided a request returns a
* status 200.
*
* @throws Exception
*/
@Test
public void givenMultiHandlerServerServer_whenHttpRequest_thenStatus200() throws Exception {
Server server = JettyServerFactory.createMultiHandlerServer();
server.start();
int statusCode = sendGetRequest();
Assert.assertEquals(200, statusCode);
server.stop();
}
/**
* Sends a default HTTP GET request to the server and returns the response
* status code.
*
* @return the status code of the response
* @throws Exception
*/
private int sendGetRequest() throws Exception {
HttpHost target = new HttpHost("localhost", JettyServerFactory.SERVER_PORT);
HttpRequest request = new HttpGet(JettyServerFactory.APP_PATH);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(target, request);
return response.getStatusLine().getStatusCode();
}
}
@@ -28,86 +28,53 @@ public class JOOLTest {
assertEquals(concat, Arrays.asList(1, 2, 3, 4, 5, 6));
assertTrue(Seq.of(1, 2, 3, 4).contains(2));
assertTrue(Seq.of(1, 2, 3, 4).containsAll(2, 3));
assertTrue(Seq.of(1, 2, 3, 4).containsAny(2, 5));
}
@Test
public void givenStreams_whenJoin_shouldHaveElementsFromTwoStreams() {
//given
// given
Stream<Integer> left = Stream.of(1, 2, 4);
Stream<Integer> right = Stream.of(1, 2, 3);
//when
// when
List<Integer> rightCollected = right.collect(Collectors.toList());
List<Integer> collect = left.filter(rightCollected::contains).collect(Collectors.toList());
//then
// then
assertEquals(collect, Arrays.asList(1, 2));
}
@Test
public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() {
assertEquals(
Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(),
Arrays.asList(tuple(1, 1), tuple(2, 2))
);
assertEquals(Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2)));
assertEquals(Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)));
assertEquals(
Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(),
Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null))
);
assertEquals(Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)));
assertEquals(
Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(),
Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3))
);
assertEquals(
Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(),
Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B"))
);
assertEquals(Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")));
}
@Test
public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() {
assertEquals(
Seq.of(1, 2, 3).cycle().limit(9).toList(),
Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3)
);
assertEquals(Seq.of(1, 2, 3).cycle().limit(9).toList(), Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3));
assertEquals(
Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())),
tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3))
);
assertEquals(Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)));
assertEquals(
Seq.of(1, 2, 3, 4).intersperse(0).toList(),
Arrays.asList(1, 0, 2, 0, 3, 0, 4)
);
assertEquals(Seq.of(1, 2, 3, 4).intersperse(0).toList(), Arrays.asList(1, 0, 2, 0, 3, 0, 4));
assertEquals(
Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(),
5
);
assertEquals(Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), 5);
assertEquals(
Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())),
tuple(Arrays.asList(3, 4), Arrays.asList(1, 2))
assertEquals(Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(3, 4), Arrays.asList(1, 2))
);
assertEquals(
Seq.of(1, 2, 3, 4).reverse().toList(),
Arrays.asList(4, 3, 2, 1)
);
assertEquals(Seq.of(1, 2, 3, 4).reverse().toList(), Arrays.asList(4, 3, 2, 1));
}
@Test
@@ -117,66 +84,38 @@ public class JOOLTest {
expectedAfterGroupBy.put(1, Arrays.asList(1, 3));
expectedAfterGroupBy.put(0, Arrays.asList(2, 4));
assertEquals(
Seq.of(1, 2, 3, 4).groupBy(i -> i % 2),
expectedAfterGroupBy
);
assertEquals(Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), expectedAfterGroupBy);
assertEquals(Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), "!abc");
assertEquals(
Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t),
"!abc"
);
assertEquals(
Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u),
"abc!"
);
assertEquals(Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), "abc!");
}
@Test
public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() {
assertEquals(
Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(),
Arrays.asList(3, 4, 5)
);
assertEquals(Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), Arrays.asList(3, 4, 5));
assertEquals(
Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(),
Arrays.asList(3, 4, 5)
);
assertEquals(Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), Arrays.asList(3, 4, 5));
}
@Test
public void givenSeq_whenZip_shouldHaveZippedSeq() {
assertEquals(
Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(),
Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c"))
);
assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")));
assertEquals(
Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(),
Arrays.asList("1:a", "2:b", "3:c")
);
assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), Arrays.asList("1:a", "2:b", "3:c"));
assertEquals(
Seq.of("a", "b", "c").zipWithIndex().toList(),
Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L))
);
assertEquals(Seq.of("a", "b", "c").zipWithIndex().toList(), Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)));
}
public Integer methodThatThrowsChecked(String arg) throws Exception {
return arg.length();
}
@Test
public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapCheckedIntoUnchecked_shouldPass() {
//when
// when
List<Integer> collect = Stream.of("a", "b", "c").map(elem -> {
try {
return methodThatThrowsChecked(elem);
@@ -186,55 +125,43 @@ public class JOOLTest {
}
}).collect(Collectors.toList());
//then
assertEquals(
collect,
Arrays.asList(1, 1, 1)
);
// then
assertEquals(collect, Arrays.asList(1, 1, 1));
}
@Test
public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() {
//when
List<Integer> collect = Stream.of("a", "b", "c")
.map(Unchecked.function(this::methodThatThrowsChecked))
.collect(Collectors.toList());
// when
List<Integer> collect = Stream.of("a", "b", "c").map(Unchecked.function(this::methodThatThrowsChecked)).collect(Collectors.toList());
//then
assertEquals(
collect,
Arrays.asList(1, 1, 1)
);
// then
assertEquals(collect, Arrays.asList(1, 1, 1));
}
@Test
public void givenFunction_whenAppliedPartially_shouldAddNumberToPartialArgument() {
//given
// given
Function2<Integer, Integer, Integer> addTwoNumbers = (v1, v2) -> v1 + v2;
addTwoNumbers.toBiFunction();
Function1<Integer, Integer> addToTwo = addTwoNumbers.applyPartially(2);
//when
// when
Integer result = addToTwo.apply(5);
//then
// then
assertEquals(result, (Integer) 7);
}
@Test
public void givenSeqOfTuples_whenTransformToLowerNumberOfTuples_shouldHaveProperResult() {
//given
// given
Seq<Tuple3<String, String, Integer>> personDetails = Seq.of(tuple("michael", "similar", 49), tuple("jodie", "variable", 43));
Tuple2<String, String> tuple = tuple("winter", "summer");
//when
// when
List<Tuple4<String, String, String, String>> result = personDetails.map(t -> t.limit2().concat(tuple)).toList();
//then
assertEquals(
result,
Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer"))
);
// then
assertEquals(result, Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer")));
}
}
@@ -1,6 +1,5 @@
package com.baeldung.jsonassert;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
@@ -62,10 +61,8 @@ public class JsonAssertUnitTest {
@Test
public void givenNestedObjects_whenAssertEquals_thenPass() throws JSONException {
String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", "
+ "state:\"LA\", zip:91601}}";
JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", "
+ "state:\"LA\", zip:91601}}", result, false);
String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}";
JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}", result, false);
}
@Test
@@ -98,32 +95,19 @@ public class JsonAssertUnitTest {
@Test
public void whenComparingSizeOfArray_thenPass() throws JSONException {
String names = "{names:[Alex, Barbera, Charlie, Xavier]}";
JSONAssert.assertEquals(
"{names:[4]}",
names,
new ArraySizeComparator(JSONCompareMode.LENIENT));
JSONAssert.assertEquals("{names:[4]}", names, new ArraySizeComparator(JSONCompareMode.LENIENT));
}
@Test
public void whenComparingContentsOfArray_thenPass() throws JSONException {
String ratings = "{ratings:[3.2,3.5,4.1,5,1]}";
JSONAssert.assertEquals(
"{ratings:[1,5]}",
ratings,
new ArraySizeComparator(JSONCompareMode.LENIENT));
JSONAssert.assertEquals("{ratings:[1,5]}", ratings, new ArraySizeComparator(JSONCompareMode.LENIENT));
}
@Test
public void givenValueMatcher_whenComparingUsingRegex_thenPass() throws IllegalArgumentException, JSONException {
JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}",
new CustomComparator(
JSONCompareMode.STRICT,
new Customization("entry.id",
new RegularExpressionValueMatcher<Object>("\\d"))));
JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher<Object>("\\d"))));
JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}",
new CustomComparator(JSONCompareMode.STRICT,
new Customization("entry.id",
new RegularExpressionValueMatcher<Object>("\\d"))));
JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher<Object>("\\d"))));
}
}
@@ -14,7 +14,7 @@ public class SafeAdditionUtilTest {
private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil();
@Test
@Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"})
@Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" })
public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
@@ -26,7 +26,7 @@ public class SafeAdditionUtilTest {
}
private Object[] parametersToTestAdd() {
return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}};
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } };
}
@Test
@@ -36,7 +36,7 @@ public class SafeAdditionUtilTest {
}
private Object[] parametersForWhenCalledWithnoParam_thenLoadByNameSafeAddAndReturn() {
return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}};
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } };
}
@Test
@@ -3,11 +3,11 @@ package com.baeldung.junitparams;
public class TestDataProvider {
public static Object[] provideBasicData() {
return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{15, -5, 10}, new Object[]{-5, -10, -15}};
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } };
}
public static Object[] provideEdgeCaseData() {
return new Object[]{new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -2, Integer.MIN_VALUE},};
return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, };
}
}
@@ -22,7 +22,7 @@ public class KafkaStreamsLiveTest {
@Test
@Ignore("it needs to have kafka broker running on local")
public void shouldTestKafkaStreams() throws InterruptedException {
//given
// given
String inputTopic = "inputTopic";
Properties streamsConfiguration = new Properties();
@@ -35,15 +35,12 @@ public class KafkaStreamsLiveTest {
// Use a temporary directory for storing state, which will be automatically removed after the test.
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath());
//when
// when
KStreamBuilder builder = new KStreamBuilder();
KStream<String, String> textLines = builder.stream(inputTopic);
Pattern pattern = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS);
KTable<String, Long> wordCounts = textLines
.flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase())))
.groupBy((key, word) -> word)
.count();
KTable<String, Long> wordCounts = textLines.flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase()))).groupBy((key, word) -> word).count();
wordCounts.foreach((word, count) -> System.out.println("word: " + word + " -> " + count));
@@ -55,7 +52,7 @@ public class KafkaStreamsLiveTest {
KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration);
streams.start();
//then
// then
Thread.sleep(30000);
streams.close();
}
@@ -8,16 +8,15 @@ import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class LocalSensitiveHashingUnitTest {
@Ignore("for simplicity of the example number of input vectors is very low, that's why LSH may yield non deterministic results")
@Test()
public void givenNVectors_whenPerformLSH_thenShouldCalculateSameHashForSimilarVectors() {
//given
boolean[] vector1 = new boolean[]{true, true, true, true, true};
boolean[] vector2 = new boolean[]{false, false, false, true, false};
boolean[] vector3 = new boolean[]{false, false, true, true, false};
// given
boolean[] vector1 = new boolean[] { true, true, true, true, true };
boolean[] vector2 = new boolean[] { false, false, false, true, false };
boolean[] vector3 = new boolean[] { false, false, true, true, false };
int sizeOfVectors = 5;
int numberOfBuckets = 10;
@@ -25,7 +24,7 @@ public class LocalSensitiveHashingUnitTest {
LSHMinHash lsh = new LSHMinHash(stages, numberOfBuckets, sizeOfVectors);
//when
// when
int[] firstHash = lsh.hash(vector1);
int[] secondHash = lsh.hash(vector2);
int[] thirdHash = lsh.hash(vector3);
@@ -34,7 +33,7 @@ public class LocalSensitiveHashingUnitTest {
System.out.println(Arrays.toString(secondHash));
System.out.println(Arrays.toString(thirdHash));
//then
// then
int lastIndexOfResult = stages - 1;
assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(secondHash[lastIndexOfResult]);
assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(thirdHash[lastIndexOfResult]);
@@ -45,4 +44,3 @@ public class LocalSensitiveHashingUnitTest {
return Math.abs(secondHash - thirdHash) < numberOfBuckets / 2;
}
}
@@ -25,8 +25,8 @@ public class MBassadorConfigurationTest implements IPublicationErrorHandler {
@Before
public void prepareTests() {
dispatcher = new MBassador<String>(this);
dispatcher.subscribe(this);
dispatcher = new MBassador<String>(this);
dispatcher.subscribe(this);
}
@Test
@@ -10,7 +10,7 @@ import static org.junit.Assert.*;
public class XORIntegrationTest {
private NeuralNetwork ann = null;
private void print(String input, double output, double actual) {
private void print(String input, double output, double actual) {
System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output);
}
@@ -1,6 +1,5 @@
package com.baeldung.pact;
import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRuleMk2;
import au.com.dius.pact.consumer.PactVerification;
@@ -23,61 +22,37 @@ import static org.assertj.core.api.Assertions.assertThat;
public class PactConsumerDrivenContractUnitTest {
@Rule
public PactProviderRuleMk2 mockProvider
= new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
@Pact(consumer = "test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return builder
.given("test GET")
.uponReceiving("GET REQUEST")
.path("/pact")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body("{\"condition\": true, \"name\": \"tom\"}")
.given("test POST")
.uponReceiving("POST REQUEST")
.method("POST")
.headers(headers)
.body("{\"name\": \"Michael\"}")
.path("/pact")
.willRespondWith()
.status(201)
.toPact();
return builder.given("test GET").uponReceiving("GET REQUEST").path("/pact").method("GET").willRespondWith().status(200).headers(headers).body("{\"condition\": true, \"name\": \"tom\"}").given("test POST").uponReceiving("POST REQUEST").method("POST")
.headers(headers).body("{\"name\": \"Michael\"}").path("/pact").willRespondWith().status(201).toPact();
}
@Test
@PactVerification()
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
//when
ResponseEntity<String> response
= new RestTemplate().getForEntity(mockProvider.getUrl() + "/pact", String.class);
// when
ResponseEntity<String> response = new RestTemplate().getForEntity(mockProvider.getUrl() + "/pact", String.class);
//then
// then
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThat(response.getHeaders().get("Content-Type").contains("application/json")).isTrue();
assertThat(response.getBody()).contains("condition", "true", "name", "tom");
//and
// and
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
String jsonBody = "{\"name\": \"Michael\"}";
//when
ResponseEntity<String> postResponse = new RestTemplate().exchange(
mockProvider.getUrl() + "/pact",
HttpMethod.POST,
new HttpEntity<>(jsonBody, httpHeaders),
String.class
);
// when
ResponseEntity<String> postResponse = new RestTemplate().exchange(mockProvider.getUrl() + "/pact", HttpMethod.POST, new HttpEntity<>(jsonBody, httpHeaders), String.class);
//then
// then
assertThat(postResponse.getStatusCode().value()).isEqualTo(201);
}
@@ -46,5 +46,4 @@ public class ApacheCommonsPairUnitTest {
immutablePair.setValue("Another One");
}
}
@@ -17,15 +17,15 @@ public class CoreJavaSimpleEntryUnitTest {
assertEquals(key.intValue(), 1);
assertEquals(value, "one");
}
@Test(expected = UnsupportedOperationException.class)
public void givenSimpleImmutableEntry_whenSetValue_thenException() {
AbstractMap.SimpleImmutableEntry<Integer, String> entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "one");
entry.setValue("two");
}
@Test
public void givenSimpleImmutableEntry_whenGetValue_thenOk() {
AbstractMap.SimpleImmutableEntry<Integer, String> entry = new AbstractMap.SimpleImmutableEntry<Integer, String>(1, "one");
@@ -86,8 +86,7 @@ public class PCollectionsUnitTest {
@Test
public void whenMapPSetMethods_thenPerformOperations() {
MapPSet pSet = HashTreePSet.empty()
.plusAll(Arrays.asList("e1", "e2", "e3", "e4"));
MapPSet pSet = HashTreePSet.empty().plusAll(Arrays.asList("e1", "e2", "e3", "e4"));
assertEquals(pSet.size(), 4);
MapPSet pSet1 = pSet.minus("e4");
@@ -35,32 +35,21 @@ public class CollectorUtilsTests {
@Test
public void givenEmptyStream_withCollectorUnique_shouldReturnEmpty() {
assertThat(Stream
.empty()
.collect(CollectorUtils.unique()), equalTo(Optional.empty()));
assertThat(Stream.empty().collect(CollectorUtils.unique()), equalTo(Optional.empty()));
}
@Test
public void givenIntegerStream_withCollectorUnique_shouldReturnUniqueValue() {
assertThat(Stream
.of(1, 2, 3)
.filter(i -> i > 2)
.collect(CollectorUtils.unique()), equalTo(Optional.of(3)));
assertThat(Stream.of(1, 2, 3).filter(i -> i > 2).collect(CollectorUtils.unique()), equalTo(Optional.of(3)));
}
@Test
public void givenIntegerStream_withUniqueNullable_shouldReturnUniqueValue() {
assertThat(Stream
.of(1, 2, 3)
.filter(i -> i > 2)
.collect(CollectorUtils.uniqueNullable()), equalTo(3));
assertThat(Stream.of(1, 2, 3).filter(i -> i > 2).collect(CollectorUtils.uniqueNullable()), equalTo(3));
}
@Test(expected = NonUniqueValueException.class)
public void givenIntegerStream_withCollectorUnique_shouldThrowNonUniqueValueException() {
Stream
.of(1, 2, 3)
.filter(i -> i > 1)
.collect(CollectorUtils.unique());
Stream.of(1, 2, 3).filter(i -> i > 1).collect(CollectorUtils.unique());
}
}
@@ -24,9 +24,7 @@ public class StreamUtilsTests {
public void givenStream_whenZipWithIndex_shouldReturnZippedStreamWithIndex() {
Stream<String> source = Stream.of("Foo", "Bar", "Baz");
List<Indexed<String>> zipped = StreamUtils
.zipWithIndex(source)
.collect(Collectors.toList());
List<Indexed<String>> zipped = StreamUtils.zipWithIndex(source).collect(Collectors.toList());
assertThat(zipped, contains(Indexed.index(0, "Foo"), Indexed.index(1, "Bar"), Indexed.index(2, "Baz")));
}
@@ -36,9 +34,7 @@ public class StreamUtilsTests {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils
.zip(streamA, streamB, (a, b) -> a + " is for " + b)
.collect(Collectors.toList());
List<String> zipped = StreamUtils.zip(streamA, streamB, (a, b) -> a + " is for " + b).collect(Collectors.toList());
assertThat(zipped, contains("A is for Apple", "B is for Banana", "C is for Carrot"));
}
@@ -49,15 +45,13 @@ public class StreamUtilsTests {
Stream<String> streamB = Stream.of("aggravating", "banausic", "complaisant");
Stream<String> streamC = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils
.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c)
.collect(Collectors.toList());
List<String> zipped = StreamUtils.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c).collect(Collectors.toList());
assertThat(zipped, contains("A is for aggravating Apple", "B is for banausic Banana", "C is for complaisant Carrot"));
}
@Test
//givenThreeStreams_whenMerge_shouldReturnMergedStream
// givenThreeStreams_whenMerge_shouldReturnMergedStream
public void givenThreeStreams_whenMerge_shouldReturnMergedStream() {
Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("apple", "banana", "carrot", "date");
@@ -69,7 +63,7 @@ public class StreamUtilsTests {
}
@Test
//givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream
// givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream
public void givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream() {
Stream<String> streamA = Stream.of("Peter", "Paul", "Mary");
Stream<String> streamB = Stream.of("A", "B", "C", "D", "E");
@@ -81,7 +75,7 @@ public class StreamUtilsTests {
}
@Test
//givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10
// givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10
public void givenInfiniteStream_whenTakeWhile10_shouldReturnStream() {
Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1);
Stream<Integer> finiteInts = StreamUtils.takeWhile(infiniteInts, i -> i < 10);
@@ -125,9 +119,7 @@ public class StreamUtilsTests {
@Test
public void giveIntegerStream_whenGroupRuns_shouldReturnListGroupItems() {
Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5);
List<List<Integer>> runs = StreamUtils
.groupRuns(integerStream)
.collect(toList());
List<List<Integer>> runs = StreamUtils.groupRuns(integerStream).collect(toList());
assertThat(runs, contains(asList(1, 1), asList(2, 2), asList(3), asList(4), asList(5)));
}
@@ -143,21 +135,17 @@ public class StreamUtilsTests {
public void givenIntegerStream_whenWindowed_shouldReturnListOfListOfItemsOfWindowSize() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils
.windowed(integerStream, 2)
.collect(toList());
List<List<Integer>> windows = StreamUtils.windowed(integerStream, 2).collect(toList());
assertThat(windows, contains(asList(1, 2), asList(2, 3), asList(3, 4), asList(4, 5)));
}
@Test
//givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip
// givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip
public void givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils
.windowed(integerStream, 3, 2)
.collect(toList());
List<List<Integer>> windows = StreamUtils.windowed(integerStream, 3, 2).collect(toList());
assertThat(windows, contains(asList(1, 2, 3), asList(3, 4, 5)));
}
@@ -166,15 +154,9 @@ public class StreamUtilsTests {
public void givenEmptyStream_whenWindowed_shouldReturnIterableWithSizeZero() {
ArrayList<Integer> ints = new ArrayList<>();
ints
.stream()
.collect(maxBy((a, b) -> a
.toString()
.compareTo(b.toString())));
ints.stream().collect(maxBy((a, b) -> a.toString().compareTo(b.toString())));
List<List<Integer>> windows = StreamUtils
.windowed(ints.stream(), 2)
.collect(toList());
List<List<Integer>> windows = StreamUtils.windowed(ints.stream(), 2).collect(toList());
assertThat(windows, iterableWithSize(0));
}
@@ -183,18 +165,14 @@ public class StreamUtilsTests {
public void givenIntegerStream_whenWindowedWithWindowSizeAndSkipAndAllowLesserSize_shouldReturnListOfListOfInteger() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils
.windowed(integerStream, 2, 2, true)
.collect(toList());
List<List<Integer>> windows = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList());
assertThat(windows, contains(asList(1, 2), asList(3, 4), asList(5)));
}
@Test
public void givenLimit_withIndices_shouldReturnLongStreamUptoLimit() {
LongStream indices = StreamUtils
.indices()
.limit(500);
LongStream indices = StreamUtils.indices().limit(500);
assertThat(indices.count(), equalTo(500));
}
@@ -17,46 +17,33 @@ import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class GitHubBasicApiLiveTest {
GitHubBasicApi gitHub;
@Before
public void init() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build();
gitHub = retrofit.create(GitHubBasicApi.class);
}
@Test
public void whenListRepos_thenExpectReposThatContainTutorials() {
try {
List<Repository> repos = gitHub
.listRepos("eugenp")
.execute()
.body();
assertThat(repos)
.isNotEmpty()
.extracting(Repository::getName).contains("tutorials");
List<Repository> repos = gitHub.listRepos("eugenp").execute().body();
assertThat(repos).isNotEmpty().extracting(Repository::getName).contains("tutorials");
} catch (IOException e) {
fail("Can not communicate with GitHub API");
}
}
@Test
public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() {
try {
List<Contributor> contributors = gitHub
.listRepoContributors("eugenp", "tutorials")
.execute()
.body();
assertThat(contributors)
.isNotEmpty()
.extracting(Contributor::getName).contains("eugenp");
List<Contributor> contributors = gitHub.listRepoContributors("eugenp", "tutorials").execute().body();
assertThat(contributors).isNotEmpty().extracting(Contributor::getName).contains("eugenp");
} catch (IOException e) {
fail("Can not communicate with GitHub API");
}
@@ -14,40 +14,28 @@ import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class GitHubRxApiTest {
GitHubRxApi gitHub;
@Before
public void init() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
gitHub = retrofit.create(GitHubRxApi.class);
}
@Test
public void whenListRepos_thenExpectReposThatContainTutorials() {
gitHub
.listRepos("eugenp")
.subscribe( repos -> {
assertThat(repos)
.isNotEmpty()
.extracting(Repository::getName).contains("tutorials");
});
gitHub.listRepos("eugenp").subscribe(repos -> {
assertThat(repos).isNotEmpty().extracting(Repository::getName).contains("tutorials");
});
}
@Test
public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() {
gitHub
.listRepoContributors("eugenp", "tutorials")
.subscribe(contributors -> {
assertThat(contributors)
.isNotEmpty()
.extracting(Contributor::getName).contains("eugenp");
});
gitHub.listRepoContributors("eugenp", "tutorials").subscribe(contributors -> {
assertThat(contributors).isNotEmpty().extracting(Contributor::getName).contains("eugenp");
});
}
}
@@ -23,15 +23,11 @@ public class GoogleSearchLiveTest {
public void whenGoogleBaeldungThenShouldSeeEugen() {
browser.get("https://www.google.com/ncr");
browser
.findElement(By.name("q"))
.sendKeys("baeldung", Keys.ENTER);
browser.findElement(By.name("q")).sendKeys("baeldung", Keys.ENTER);
new WebDriverWait(browser, 5).until(visibilityOfElementLocated(By.cssSelector("._ksh")));
assertThat(browser
.findElement(By.cssSelector("._ksh"))
.getText(), containsString("Eugen (Baeldung)"));
assertThat(browser.findElement(By.cssSelector("._ksh")).getText(), containsString("Eugen (Baeldung)"));
}
}
@@ -43,9 +43,6 @@ public class GithubRestUserAPISteps {
private static HttpResponse getGithubUserProfile(String api, String username) throws IOException {
HttpUriRequest request = new HttpGet(String.format(api, username));
return HttpClientBuilder
.create()
.build()
.execute(request);
return HttpClientBuilder.create().build().execute(request);
}
}
@@ -33,7 +33,7 @@ public class MemberStatusSteps {
@Pending
@Step("When the member exchange {}")
public void aMemberExchangeA(Commodity commodity) {
//TODO
// TODO
}
@Pending
@@ -24,9 +24,7 @@ public class GoogleSearchPageObject extends PageObject {
}
public void resultMatches(String expected) {
withTimeoutOf(5, SECONDS)
.waitFor(result)
.waitUntilVisible();
withTimeoutOf(5, SECONDS).waitFor(result).waitUntilVisible();
assertThat(result.getText(), containsString(expected));
}
@@ -10,12 +10,8 @@ import net.thucydides.core.annotations.DefaultUrl;
@DefaultUrl("https://www.google.com/ncr")
class GoogleSearchPage extends PageObject {
static final Target SEARCH_RESULT_TITLES = Target
.the("search results")
.locatedBy("._ksh");
static final Target SEARCH_RESULT_TITLES = Target.the("search results").locatedBy("._ksh");
static final Target SEARCH_INPUT_BOX = Target
.the("search input box")
.locatedBy("#lst-ib");
static final Target SEARCH_INPUT_BOX = Target.the("search input box").locatedBy("#lst-ib");
}
@@ -13,9 +13,6 @@ public class GoogleSearchResults implements Question<List<String>> {
}
public List<String> answeredBy(Actor actor) {
return Text
.of(GoogleSearchPage.SEARCH_RESULT_TITLES)
.viewedBy(actor)
.asList();
return Text.of(GoogleSearchPage.SEARCH_RESULT_TITLES).viewedBy(actor).asList();
}
}
@@ -11,10 +11,7 @@ public class SearchForKeyword implements Task {
@Step("{0} searches for '#keyword'")
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(Enter
.theValue(keyword)
.into(GoogleSearchPage.SEARCH_INPUT_BOX)
.thenHit(Keys.RETURN));
actor.attemptsTo(Enter.theValue(keyword).into(GoogleSearchPage.SEARCH_INPUT_BOX).thenHit(Keys.RETURN));
}
private String keyword;
@@ -24,9 +21,7 @@ public class SearchForKeyword implements Task {
}
public static Task of(String keyword) {
return Instrumented
.instanceOf(SearchForKeyword.class)
.withProperties(keyword);
return Instrumented.instanceOf(SearchForKeyword.class).withProperties(keyword);
}
}
@@ -17,9 +17,7 @@ public class StartWith implements Task {
@Step("{0} starts a google search")
public <T extends Actor> void performAs(T t) {
t.attemptsTo(Open
.browserOn()
.the(googleSearchPage));
t.attemptsTo(Open.browserOn().the(googleSearchPage));
}
}
@@ -15,9 +15,7 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS;
@RunWith(Suite.class)
@Suite.SuiteClasses({
AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class
})
@Suite.SuiteClasses({ AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class })
public class AdderClassDirtiesContextIntegrationTest {
@RunWith(SerenityRunner.class)
@@ -52,7 +50,7 @@ public class AdderClassDirtiesContextIntegrationTest {
@Test
public void givenNumber_whenAdd_thenSumWrong() {
super.whenAdd_thenSummedUp(); //expecting zero
super.whenAdd_thenSummedUp(); // expecting zero
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
super.whenAccumulate_thenSummedUp();
super.whenAdd_thenSumWrong();
@@ -64,7 +62,7 @@ public class AdderClassDirtiesContextIntegrationTest {
@Test
public void givenNumber_whenAdd_thenSumWrong() {
super.whenAdd_thenSummedUp(); //expecting zero
super.whenAdd_thenSummedUp(); // expecting zero
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
super.whenAccumulate_thenSummedUp();
super.whenAdd_thenSumWrong();
@@ -25,7 +25,8 @@ public class AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest {
private AdderConstructorDependencySteps adderSteps;
@Autowired private AdderService adderService;
@Autowired
private AdderService adderService;
@Before
public void init() {
@@ -38,7 +39,8 @@ public class AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest {
adderSteps.summedUp();
}
@Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@Rule
public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
@@ -23,7 +23,8 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
@ContextConfiguration(classes = AdderService.class)
public class AdderMethodDirtiesContextInitWorkaroundIntegrationTest {
@Steps private AdderServiceSteps adderServiceSteps;
@Steps
private AdderServiceSteps adderServiceSteps;
@Before
public void init() {
@@ -36,7 +37,8 @@ public class AdderMethodDirtiesContextInitWorkaroundIntegrationTest {
adderServiceSteps.summedUp();
}
@Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@Rule
public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
@@ -22,7 +22,8 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
@ContextConfiguration(classes = AdderService.class)
public class AdderMethodDirtiesContextIntegrationTest {
@Steps private AdderServiceSteps adderServiceSteps;
@Steps
private AdderServiceSteps adderServiceSteps;
@Test
public void _1_givenNumber_whenAdd_thenSumWrong() {
@@ -30,7 +31,8 @@ public class AdderMethodDirtiesContextIntegrationTest {
adderServiceSteps.sumWrong();
}
@Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@Rule
public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
@@ -41,11 +41,14 @@ public class AdderMethodRuleIntegrationTest {
LOG.info("adder after test: {}", adder);
}
@Rule public SpringIntegrationMethodRule springMethodIntegration = new SpringIntegrationMethodRule();
@Rule
public SpringIntegrationMethodRule springMethodIntegration = new SpringIntegrationMethodRule();
@Steps private AdderSteps adderSteps;
@Steps
private AdderSteps adderSteps;
@Value("#{props['adder']}") private int adder;
@Value("#{props['adder']}")
private int adder;
private static int staticAdder;
@@ -21,7 +21,8 @@ public class AdderMockMvcIntegrationTest {
RestAssuredMockMvc.standaloneSetup(new PlainAdderController());
}
@Steps AdderRestSteps steps;
@Steps
AdderRestSteps steps;
@Test
public void givenNumber_whenAdd_thenSummedUp() throws Exception {
@@ -14,7 +14,8 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
@RunWith(SerenityRunner.class)
public class AdderServiceIntegrationTest {
@Steps private AdderServiceSteps adderServiceSteps;
@Steps
private AdderServiceSteps adderServiceSteps;
@Test
public void givenNumber_whenAdd_thenSummedUp() {
@@ -15,9 +15,11 @@ import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:adder-beans.xml")
public class AdderSpringSerenityRunnerIntegrationTest {
@Steps private AdderSteps adderSteps;
@Steps
private AdderSteps adderSteps;
@Value("#{props['adder']}") private int adder;
@Value("#{props['adder']}")
private int adder;
@Test
public void givenNumber_whenAdd_thenSummedUp() {
@@ -6,7 +6,7 @@ import org.jbehave.core.annotations.BeforeStory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = {AdderController.class, AdderService.class})
@ContextConfiguration(classes = { AdderController.class, AdderService.class })
public class AdderTest extends SerenityStory {
@Autowired
@@ -18,29 +18,18 @@ public class AdderRestSteps {
@Step("get the current number")
public void givenCurrentNumber() throws UnsupportedEncodingException {
currentNum = Integer.valueOf(given()
.when()
.get("/adder/current")
.mvcResult()
.getResponse()
.getContentAsString());
currentNum = Integer.valueOf(given().when().get("/adder/current").mvcResult().getResponse().getContentAsString());
}
@Step("adding {0}")
public void whenAddNumber(int num) {
mockMvcResponse = given()
.queryParam("num", num)
.when()
.post("/adder");
mockMvcResponse = given().queryParam("num", num).when().post("/adder");
currentNum += num;
}
@Step("got the sum")
public void thenSummedUp() {
mockMvcResponse
.then()
.statusCode(200)
.body(equalTo(currentNum + ""));
mockMvcResponse.then().statusCode(200).body(equalTo(currentNum + ""));
}
}
@@ -13,7 +13,8 @@ import static org.junit.Assert.assertNotEquals;
@ContextConfiguration(classes = AdderService.class)
public class AdderServiceSteps {
@Autowired private AdderService adderService;
@Autowired
private AdderService adderService;
private int givenNumber;
private int base;
@@ -11,7 +11,8 @@ import org.jbehave.core.annotations.When;
*/
public class AdderStory {
@Steps AdderRestSteps restSteps;
@Steps
AdderRestSteps restSteps;
@Given("a number")
public void givenANumber() throws Exception {
@@ -10,22 +10,11 @@ import java.text.SimpleDateFormat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class SmooksIntegrationTest {
private static final String EDIFACT_MESSAGE =
"UNA:+.? '\r\n" +
"UNH+771+IN_PROGRESS+2018-01-14'\r\n" +
"CTA+CompanyX+1234567'\r\n" +
"LIN+1+PX1234+9.99'\r\n" +
"LIN+2+RX990+120.32'\r\n";
private static final String EMAIL_MESSAGE =
"Hi,\r\n" +
"Order number #771 created on 2018-01-14 is currently in IN_PROGRESS status.\r\n" +
"Consider contact supplier \"CompanyX\" with phone number: \"1234567\".\r\n" +
"Order items:\r\n" +
"1 X PX1234 (total price 9.99)\r\n" +
"2 X RX990 (total price 240.64)\r\n";
private static final String EDIFACT_MESSAGE = "UNA:+.? '\r\n" + "UNH+771+IN_PROGRESS+2018-01-14'\r\n" + "CTA+CompanyX+1234567'\r\n" + "LIN+1+PX1234+9.99'\r\n" + "LIN+2+RX990+120.32'\r\n";
private static final String EMAIL_MESSAGE = "Hi,\r\n" + "Order number #771 created on 2018-01-14 is currently in IN_PROGRESS status.\r\n" + "Consider contact supplier \"CompanyX\" with phone number: \"1234567\".\r\n" + "Order items:\r\n"
+ "1 X PX1234 (total price 9.99)\r\n" + "2 X RX990 (total price 240.64)\r\n";
@Test
public void givenOrderXML_whenConvert_thenPOJOsConstructedCorrectly() throws Exception {
@@ -33,14 +22,11 @@ public class SmooksIntegrationTest {
OrderConverter xmlToJavaOrderConverter = new OrderConverter();
Order order = xmlToJavaOrderConverter.convertOrderXMLToOrderObject("/smooks/order.xml");
assertThat(order.getNumber(),is(771L));
assertThat(order.getStatus(),is(Status.IN_PROGRESS));
assertThat(order.getCreationDate(),is(new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-14")));
assertThat(order.getSupplier(),is(new Supplier("CompanyX","1234567")));
assertThat(order.getItems(),containsInAnyOrder(
new Item("PX1234",9.99,1),
new Item("RX990",120.32,2))
);
assertThat(order.getNumber(), is(771L));
assertThat(order.getStatus(), is(Status.IN_PROGRESS));
assertThat(order.getCreationDate(), is(new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-14")));
assertThat(order.getSupplier(), is(new Supplier("CompanyX", "1234567")));
assertThat(order.getItems(), containsInAnyOrder(new Item("PX1234", 9.99, 1), new Item("RX990", 120.32, 2)));
}
@@ -51,20 +37,20 @@ public class SmooksIntegrationTest {
assertThat(validationResult.getErrors(), hasSize(1));
// 1234567 didn't match ^[0-9\\-\\+]{9,15}$
assertThat(validationResult.getErrors().get(0).getFailRuleResult().getRuleName(),is("supplierPhone"));
assertThat(validationResult.getErrors().get(0).getFailRuleResult().getRuleName(), is("supplierPhone"));
}
@Test
public void givenOrderXML_whenApplyEDITemplate_thenConvertedToEDIFACT() throws Exception {
OrderConverter orderConverter = new OrderConverter();
String edifact = orderConverter.convertOrderXMLtoEDIFACT("/smooks/order.xml");
assertThat(edifact,is(EDIFACT_MESSAGE));
assertThat(edifact, is(EDIFACT_MESSAGE));
}
@Test
public void givenOrderXML_whenApplyEmailTemplate_thenConvertedToEmailMessage() throws Exception {
OrderConverter orderConverter = new OrderConverter();
String emailMessage = orderConverter.convertOrderXMLtoEmailMessage("/smooks/order.xml");
assertThat(emailMessage,is(EMAIL_MESSAGE));
assertThat(emailMessage, is(EMAIL_MESSAGE));
}
}
@@ -1,6 +1,5 @@
package com.baeldung.stm;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
@@ -16,34 +15,34 @@ public class AccountTest {
@Test
public void givenAccount_whenDecrement_thenShouldReturnProperValue() {
//given
// given
Account a = new Account(10);
//when
// when
a.adjustBy(-5);
//then
// then
assertThat(a.getBalance()).isEqualTo(5);
}
@Test(expected = IllegalArgumentException.class)
public void givenAccount_whenDecrementTooMuch_thenShouldThrow() {
//given
// given
Account a = new Account(10);
//when
// when
a.adjustBy(-11);
}
@Test
public void givenTwoThreads_whenBothApplyOperation_thenShouldThrow() throws InterruptedException {
//given
// given
ExecutorService ex = Executors.newFixedThreadPool(2);
Account a = new Account(10);
CountDownLatch countDownLatch = new CountDownLatch(1);
AtomicBoolean exceptionThrown = new AtomicBoolean(false);
//when
// when
ex.submit(() -> {
try {
countDownLatch.await();
@@ -74,44 +73,44 @@ public class AccountTest {
ex.awaitTermination(1, TimeUnit.SECONDS);
ex.shutdown();
//then
// then
assertTrue(exceptionThrown.get());
}
@Test
public void givenTwoAccounts_whenFailedWhileTransferring_thenShouldRollbackTransaction() {
//given
// given
final Account a = new Account(10);
final Account b = new Account(10);
//when
// when
a.transferTo(b, 5);
//then
// then
assertThat(a.getBalance()).isEqualTo(5);
assertThat(b.getBalance()).isEqualTo(15);
//and
// and
try {
a.transferTo(b, 20);
} catch (final IllegalArgumentException e) {
System.out.println("failed to transfer money");
}
//then
// then
assertThat(a.getBalance()).isEqualTo(5);
assertThat(b.getBalance()).isEqualTo(15);
}
@Test
public void givenTwoThreads_whenBothTryToTransfer_thenShouldNotDeadlock() throws InterruptedException {
//given
// given
ExecutorService ex = Executors.newFixedThreadPool(2);
final Account a = new Account(10);
final Account b = new Account(10);
CountDownLatch countDownLatch = new CountDownLatch(1);
//when
// when
ex.submit(() -> {
try {
countDownLatch.await();
@@ -134,10 +133,9 @@ public class AccountTest {
ex.awaitTermination(1, TimeUnit.SECONDS);
ex.shutdown();
//then
// then
assertThat(a.getBalance()).isEqualTo(1);
assertThat(b.getBalance()).isEqualTo(19);
}
}

Some files were not shown because too many files have changed in this diff Show More