Assert that Collection contains 2 Objects with same property using matchers [duplicate] - java

This question already has answers here:
What is the idiomatic Hamcrest pattern to assert that each element of an iterable matches a given matcher?
(3 answers)
Closed 8 years ago.
I have the following scenario, where I want to test someFunction():
Collection<MyObject> objects = someFunction(someInput);
assertThat(objects , contains(hasProperty("property", is(propertyIWantToTest))));
This works fine if Collection<MyObject> objects should have just 1 MyObject object according to someInput which is passed to someFunction().
However, there are some cases for someInput that the Collection<MyObject> objects should have 2 or more MyObject object containg the same propertyIWantToTest object.
Is there a way to use Hamcrest matchers to test that?
Here's something closer to what I'm willing to achieve:
assertThat(objects , contains(exactlyTwoTimes(hasProperty("property", is(propertyIWantToTest)))));

If you want to verify that every item has that property, and that there are exactly two items, then use everyItem and hasSize:
assertThat(objects, everyItem(hasProperty("property", is(propertyIWantToTest))));
assertThat(objects, hasSize(2));
If you want to specifically test the contents of the collection, but it just so happens that both expected items are the same, use a variable and containsInAnyOrder:
Matcher<MyObject> m = hasProperty("property", is(propertyIWantToTest));
assertThat(objects, containsInAnyOrder(m, m));

Related

finding a key inside a treeMap without case sensitivity [duplicate]

This question already has answers here:
How to make a CaseInsensitiveConcurrentMap?
(2 answers)
Closed 2 years ago.
So basically I have treeMap and I want to find keys in it the thing is that searching for ABC or Abc or aBc or abC or ABc or AbCor aBC it should return true in the containsKey after using some comparator i think.
The thing is that i already tried to covert the String all into lower case and upper case but sometimes i need the key to be like aBC because i need to print the key and printing abc and ABC or ABc are different things.
So do you know another way to do this?
Use toLower() when adding to the map, and also when searching. But, you'll have to add special handling if you want to be able to store distinct values for keys that differ only in upper/lower case.
If you need to keep the original case you'll have to modify the value object to store it.
You might also want to subclass TreeMap and override the put and get methods to take care of the toLower() calls. Remember to override ALL methods that get or put values.

List.of() — Why offer an empty list of elements that can't be add/removed/edited? [duplicate]

This question already has answers here:
Is there any practical application/use case when we create empty immutable list / set / map
(4 answers)
Closed 4 years ago.
One of the Java 9 features I've tested is the List.of() to create an unmodifiable list. I wonder - What is the purpose of this method if it returns an empty list of elements that can't be add / removed / edited?
The only thing that i was able to think of is to compare this list to another empty list, but then why not just to use someList.isEmpty()?
First of all, List.of() does not create any new object. It refers to a static final constant, as we can see in the OpenJDK source code List.java.
static <E> List<E> of() {
return ImmutableCollections.List0.instance();
}
…and in the source code for java.util.ImmutableCollections.List0.instance():
static <T> List0<T> instance()
return (List0<T>) INSTANCE;
}
List.of() can used to return an empty list instead of a null, which has numerous advantages:
elimates the risk of NullPointerException
the client code does not have to check for null
As far as I know, the primary use of this method is for debugging. If you want to test your code on some list (say summing the elements), it is convenient to have a method that quickly creates a list. Because of the internal implementation the list is not mutable, but that's okay since we're just using it to test your code once.
UPDATE:
Since List.of(E e1, E e2, ...) are used for debugging, there is no reason not to include List.of() with no arguments, as often when debugging you will check for edge cases and see if your code also works for empty lists.

How come this java code isn't throwing an exception? [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 6 years ago.
I was messing around with lists and got to this code (its a part of the main):
List l1 = new ArrayList<Object>();
List l2 = new ArrayList<String>();
Object t = "a";
l1.add("a");
l2.add(t);
System.out.println(l1.equals(l2));
System.out.println(l2.get(0));
The dynamic type of l2 is ArrayList(type:String) , but I managed to add an Object to it. Moreover, it said the lists are equal. I thought that maybe it casts it to String somehow, but then I tried:
Object t = 9;
And it still worked. Pretty sure it has something to do with the list being a raw type, but still, I can't understand how I can add an object to an ArrayList(type: String). Thanks in advance.
You are declare l2 as raw list. Thus you can add element of any type.
Regarding the equality of the l2 and l1 lists the documentation of equals method on the arraylist class says:
Compares the specified object with this list for equality. Returns
true if and only if the specified object is also a list, both lists
have the same size, and all corresponding pairs of elements in the two
lists are equal
.
The String class is a child of the Object class, so there is an inheritance of objects.
You should not use "equals" with inheritance.
More here : Why should I not use equals with inheritance?
The thing is, the object could be converted back to string, either through an explicit conversion (in this case I'd call it unboxing, like in C#), or by the Java analog of C#'s ToString() method. Either way, the object could successfully be converted to a string so the runtime doesn't complain.
If t was a number converted to an object, either you'd get an exception or you'd get a string representation of that number.
List equality must have been overridden to call the .equals method of the objects in each list.

Most efficient way to check if an array contains a value in Java? [duplicate]

This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 6 years ago.
I have a similar logic for a method in a Java Class (not the real code, this is simplified for example purposes).
private Boolean method(Boolean booleanValue, SomeObject object) {
return booleanValue ? Arrays.asList(object.getStringsArray()).contains("string") : false;
}
A collaborator who assigned himself to check the PR gave the following comment:
This is inefficient. It is creating a new data structure only to iterate it and check if there is a certain string.
The getStringsArray() method returns a String[], so will using a for-loop be better than Arrays.asList()?
Which way is more efficient to achieve this?
Your co-worker is incorrect when they assert that your method is creating a new data structure.
If you look at the API for Arrays.asList(), it says that it
Returns a fixed-size list backed by the specified array.
There is no reason to write your own code to iterate over the array when you can just wrap a List around it, and use its built-in methods.

Comparing two list of objects in JUnit [duplicate]

This question already has answers here:
AssertEquals 2 Lists ignore order
(10 answers)
Java Compare Two Lists
(11 answers)
Closed 6 years ago.
I am writing JUnit Test case for my java project and using Coverage Tool to check the lines of code are covered. The problem is: I've two list of objects. I need to compare the results of object to be equal using assertTrue or any other possible assert statements. I am getting error like Assertion Error by using below assert statements. Is there any solution to compare two lists easily?
//actual
List<ProjectData> actuals = ProjectManagerDao.getProjects("x", "y", "z");
// expected
List<ProjectData> expecteds = new ArrayList<>();
ProjectData p1 = new ProjectData();
p1.setId("a");
p1.setName("b");
expecteds.add(p1);
assertTrue(JsonProvider.getGson().toJson(actuals).equalsIgnoreCase(JsonProvider.getGson().toJson(expecteds)));
//or
assertTrue(actuals.equalIgnoreCase(expeteds);//Not working for list of objects but working for comparing two strings
This differs from Java Compare Two Lists in that I need to be able to assert equality in jUnit, not just compare the lists.
Use Assert.assertArrayEquals(Object[] expecteds, Object[] actuals) method to compare two array for content equality:
Assert.assertArrayEquals(expected.toArray(), actuals.toArray());
equals method compares arrays for being the same reference so it's not suitable in test cases.
For your other question: Remember to use org.junit.Assert not junit.Assert which became obsolete.
In short: there is exactly one assert that one needs when writing JUnit tests: assertThat
You just write code like
assertThat("optional message printed on fails", actualArrayListWhatever, is(expectedArrayListWhatever))
where is() is a hamcrest matcher.
This approach does work for all kinds of collections and stuff; and it does the natural "compare element by element" thing (and there are plenty of other hamcrest matcher that one can use for more specific testing; and it is also pretty easy to write your own matchers).
( seriously; I have not seen a single case where assertThat() would not work; or would result in less readable code )
You can use
Assert.assertEquals(java.lang.Object expected, java.lang.Object actual);
example:
ArrayList<String> list1 = new ArrayList<>();
list1.add("hello");
ArrayList<String> list2 = new ArrayList<>();
list2.add("hello");
Assert.assertEquals(list1, list2);
source: Junit API
or if you want to use the arrays comparison method you can as below
ArrayList<String> list1;
ArrayList<String> list2;
Assert.assertArrayEquals(list1.toArray(), list2.toArray());
I would recommend you to use the assertEquals method.
PS: (the user defined objects stored inside the list should have the equals and hashcode methods overridden)

Categories

Resources