Collection test in java

Complete Collection Framework Test

This Test will cover the Complete Collections Framework including Collection classes and interface, Working with Map, Legacy Classes, Comparator, Iterator and ListIterator.

A. object type data B. primitive type data
C. string type data D. All of the above
A. IllegalArgumentException B. IllegalStateException
C. ClassCastException D. NullPointerException
A. returns an object stored at the specified index
B. stores an object at the specified index
C. returns a list containing elements between specified index and end in the collection.
D. none of the above.

Q. Which of the following interface guarantees that no duplicates elements are stored and all elements are accessed in natural order ?

A. ArrayList class extends AbstractList class and implements the List interface
B. ArrayList supports dynamic array that can grow as needed
C. ArrayLists are synchronized.
D. It can coontain Duplicate elements and maintains the insertion order
A. TreeSet extends AbstractList class and implements the List interface.
B. Access and retrieval times are quite slow.
C. TreeSet stores elements sorted ascending order
D. Uses a LinkedList structure to store elements
Читайте также:  What is class constructor in python
A. java.util.HashMap B. java.util.Hashtable
C. java.util.LinkedHashMap D. java.util.LinkedList
A. Iterator interface B. ListIterator interface
C. Enumeration interface D. None of the above
HashMap class extends AbstractMap and implements Map interface.
HashMap class is not synchronized.
HashMap uses a hashtable to store the map.
HashMap maintain order of its element.

Q. Which of the following class provide the facility to specify default value that is used when no value is associated with a certain key ?

Have doubt related to any question?

Having second thoughts for any code related question?

Try executing the code in our Code Playground

Источник

Testing Java Collections with AssertJ.

Testing Collections in Java? You can say “Not a big deal”. I agree, but, for example, a comparison of two Lists of custom objects can be painful and it is not the only problem you can run into. Let’s dive into fluent assertions java library “AssertJ”, that can make your life easier and your tests more reliable and readable. Of course, you can use it not only for testing Collections’, but in this article we will focus on testing Lists, Sets, and Maps and will use only the basic AssertJ module – “AssertJ-core”.

Adding dependencies and imports.

testImplementation 'org.assertj:assertj-core:3.13.2'
<dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.13.2</version> <scope>test</scope> </dependency>
import static org.fest.assertions.Assertions.assertThat;

Testing Lists with AssertJ

We’re going to test List of Strings, Integers and custom POJOs. For testing List of custom objects lets create class Cat, that contains 3 fields(name, age, and breed), constructor and all getters and setters. Code of this class will be omitted for brevity.

import static org.assertj.core.api.Assertions.assertThat; public class ListsAssertJTest < private List<String> colors; private List<Cat> cats; private List<Integer> numbers; @Before public void setUp() throws Exception < colors = new ArrayList<>(); cats = new ArrayList<>(); numbers = new ArrayList<>(); cats.add(new Cat("Mia", 6, "Birman")); cats.add(new Cat("Totoro", 2, "Domestic")); cats.add(new Cat("Booboo", 10, "Maine Coon")); >// Testing the List<String> @Test public void assertThatColorsListContainsExpectedValues() < colors.add("white"); colors.add("blue"); colors.add("red"); // Here we asserting if "containsExactly()" contains all exactly the same values // and in the same order as in the List "colors". In the "as" is the message-description, // that we'll see if the test will not pass. // We can put "as" before each method, for more readable Error messages. assertThat(colors) .as("List colors should contain exactly [\"blue\", \"white\", \"red\"]") .containsExactly("white", "blue", "red"); // In this test we are checking if the List "colors" isn't empty, has size = 3, // does not have duplicates, contains specific values, starts with "red", // ends with "blue", etc. // It is pretty awesome, that it is obvious even for a non-technical person, isn't it?:) assertThat(colors) .isNotEmpty() .hasSize(3) .doesNotHaveDuplicates() .contains("white", "blue", "red") .endsWith("red") .startsWith("white") .containsSequence("white", "blue") .containsExactly("white", "blue", "red") .doesNotContain("black", "orange"); >// Testing the List<Integer> @Test public void assertThatNumbersListContainsExpectedValues() < numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5); // the same assertion as in the test below, but for List of Integers // we're checking if List "numbers" is not empty, has size = 5, // doesn't have duplicates contains 3, 2, 1, 4 and 5 in any order, // ends with 5, starts with 1, and contains exactly 1, 2, 3, 4, 5. assertThat(numbers) .isNotEmpty() .hasSize(5) .doesNotHaveDuplicates() .contains(3, 2, 1, 4, 5) .endsWith(5) .startsWith(1) .containsSequence(3, 4) .containsExactly(1, 2, 3, 4, 5); >// Testing List<Cat> @Test public void assertThatCatsListContainsExpectedValues() < // asserting if List<Cat> cats is not empty, has size 3 assertThat(cats).isNotEmpty().hasSize(3); // "extracting" is using for extracting from object specific field. // In this case "name". You can either use method reference or // lambda expression in "extracting". // "contains" is using for checking if there are specific names // in the List "cats". The test will pass if our List "cats" // contains cats with given names in any order assertThat(cats).extracting(Cat::getName).contains("Totoro", "Mia"); // same case as in the test above, but this test will pass // when at least one name from "contains" // will match the name of the cat from the List. assertThat(cats).extracting(Cat::getName).containsAnyOf("Mia", "Mary"); // similar to the two tests above, but "containsExactly" will pass // only when it will contain all names of cats from the List "cats" // in the order that they are in that List. // "doesNotContainNull" checking if there are null objects in the "cats" assertThat(cats) .extracting(Cat::getName) .containsExactly("Mia", "Totoro", "Booboo") .doesNotContainNull(); // in this test we're checking if it is empty, size and age of cats assertThat(cats).isNotEmpty().hasSize(3).extracting(Cat::getAge).contains(6, 2, 10); // in the test below we're checking if the List isn't empty, // has size = 3, and extracting cats' breeds. // Then we're checking if we don't have a cat of a breed // "Sphynx" in the list, and if we do have cats of breeds // "Birman", "Domestic", and "Maine Coon" assertThat(cats) .isNotEmpty() .hasSize(3) .extracting(cat -> cat.getBreed()) .doesNotContain("Sphynx") .contains("Birman", "Domestic", "Maine Coon"); >@Test public void assertIfSpecificObjectsOfTheListEqualsToGiven() < // creating a cat "mia" with the same values, that the cats.get(0) Cat mia = new Cat("Mia", 6, "Birman"); // asserting that cats.get(0) has the all fields with the same values as "mia" assertThat(cats.get(0)).usingRecursiveComparison().isEqualTo(mia); // changing the age of "mia" mia.setAge(1); // asserting that the cats.get(0) has the same values as "mia" ignoring the field "age" assertThat(cats.get(0)).usingRecursiveComparison().ignoringFields("age").isEqualTo(mia); // we can also create Predicate and assert if the actual object matches the given predicate assertThat(cats.get(0)).matches(c -> c.getAge() > 3); >>

Testing Sets with AssertJ

Take a look at “SetsAssertJTest” and methods I was using to test Set of Strings and Set of custom POJOs.

import static org.assertj.core.api.Assertions.assertThat; public class SetsAssertJTest < private Set<String> colors; private Set<Cat> cats; @Before public void setUp() throws Exception < colors = new HashSet<>(); cats = new HashSet<>(); >@Test public void assertThatColorsListContainsExpectedValues() < colors.add("white"); colors.add("blue"); colors.add("red"); // Testing Sets is pretty similar to testing Lists. // In this test we checking if the Set "colors" is not empty, has size 3, contains "blue" and // "red", // contains any of these 3 colors("blue", "yellow", "brown"), // contains everything from these colors("blue", "white", "red") in any order, // doesn't contain sequence of these colors("yellow", "brown"), // and also doesn't contain "black" color. assertThat(colors) .isNotEmpty() .hasSize(3) .contains("blue", "red") .containsAnyOf("blue", "yellow", "brown") .containsExactlyInAnyOrder("blue", "white", "red") .doesNotContainSequence("yellow", "brown") .doesNotContain("black"); >@Test public void assertThatCatsListContainsExpectedValues() < cats.add(new Cat("Mia", 6, "Birman")); cats.add(new Cat("Totoro", 2, "Domestic")); cats.add(new Cat("Booboo", 10, "Maine Coon")); // In this test we're checking if the Set of Cat objects isn't empty, // has size 3, then with help of "extracting" we extract names from cats' objects // using method references. After that we're checking if names contain // "Mia", "Totoro", and "Booboo", and using "allMatch" we create Predicate // and checking if all cat names have length greater than 2, // and using "anyMatch" create a Predicate for checking if // any of cats' names starts from "To". // Also we're checking if The Set doesn't contain a cat // with the name "Bella". assertThat(cats) .isNotEmpty() .hasSize(3) .extracting(Cat::getName) .contains("Mia", "Totoro", "Booboo") .allMatch(n -> n.length() > 2) .anyMatch(n -> n.startsWith("To")) .doesNotContain("Bella"); // In this test we extracting age of cats and using "filteredOn" // filter cats and keep only that objects, that have age greater than 2. // Then we're extracting names and chacking if they contain only "Mia" and "Booboo". assertThat(cats) .filteredOn(c -> c.getAge() > 2) .extracting(Cat::getName) .containsOnly("Mia", "Booboo"); // In this test we checking if the cats is exactly instance of HashSet // also extracting cat's breeds using lambda expression and checking // if they contain "Birman", "Domestic" and "Maine Coon". assertThat(cats) .isExactlyInstanceOf(HashSet.class) .extracting(cat -> cat.getBreed()) .contains("Birman", "Domestic", "Maine Coon"); >>

Testing Maps with AssertJ.

Conclusion

Using “AssertJ” you can test Java Collections easily, even if it is Collection of custom objects. It has a huge variety of methods that you can use for this purpose, that’ll make your tests bullet-proof. AssertJ also provides helpful error messages, improves tests’ readability and is easy to use within your favorite IDE. In this article, we saw the most useful assertion methods and even created different types of matchers. But there are even more methods in AssertJ you can explore, find them here. Happy testing!

Источник

Common assertions for Java collections in AssertJ

Hello! As part of Java collection series, I decided to write this small post to list some of most common assertion methods from AssertJ, that can be used to test Java collections.

Common collection assertions

This section presents most common assertions, used with Java collections. Examples are illustrated using array-based lists, that are most used Java data structures.

Collection contains the element

  • contains(E e, int index) = checks that the element presents on the specific position
  • contains(E. elements) = accepts varargs, e.g. one or more elements and checks for their presence in any order

Take a look on the code snippet below:

@Test public void containsElementTest() ListInteger> numbers = Lists.newArrayList(1, 52, 12, 39, 45, 98, 100, 565, 6, 13); assertThat(numbers).contains(12); assertThat(numbers).doesNotContain(50); > 

Collection contains elements in any order

In order to verify, that collection contains a group of elements, it is possible to use two scenarios:

  • Use contains(E.. elements) method and supply elements as varargs
  • Use contains(Iterable i) method that accepts another collection and validates that all elements are contained inside the original one in any order

Here is the example of using containsAll():

@Test public void containsAllElementsNoMatterOrderTest() ListInteger> numbers = Lists.newArrayList(1, 52, 12, 39, 45, 98, 100, 565, 6, 13); ListInteger> values = Lists.newArrayList(52, 39, 12, 1, 100); assertThat(numbers).containsAll(values); > 

Collection contains elements in the specific order

Another case is to validate, that the collection contains not only all specified elements, but also keep the specific order. To do this, it is possible to use containsExactlyElementsOf() method. It accepts an iterable and verifies that actual collection contains all the elements of the given iterable and nothing else in the same order.

Take a look on following example:

@Test public void containsAllElementsInOrderTest() ListInteger> numbers = Lists.newArrayList(1, 52, 12, 39, 45, 98, 100, 565, 6, 13); ListInteger> values = Lists.newArrayList(numbers); assertThat(numbers).containsExactlyElementsOf(values); > 

Collection contains no duplicates

Not all Java collections allows duplicates: sets, for example, check for inserted elements and do not allow duplicates. Other collections, like lists, do not offer this functionality. In this case, when you need to asserts that the collection does not have duplicate elements, it is advised to use doesNotHaveDuplicates() method:

@Test public void noDuplicatesTest() ListInteger> numbers = Lists.newArrayList(1, 52, 12, 39, 45, 98, 100, 565, 6, 13); assertThat(numbers).doesNotHaveDuplicates(); > 

Collection contains the element only once

The extended case of the last situation is to check that element is presented only once. Technically, contains() method allows duplicate entities, so to check that element does not repeat, use containsOnlyOnce() assertion.

Observe the code snippet below:

@Test public void containsOnlyOnceTest() ListInteger> numbers = Lists.newArrayList(1, 1, 52, 12, 12, 45, 45); assertThat(numbers).containsOnlyOnce(52); > 

Source code

You can find the full source code for this post in this github repository. If you have questions regarding this post, don’t hesitate to contact me. Have a nice day!

Источник

JUnit – Как протестировать список

Во-первых, исключите из комплекта JUnit копию hamcrest-core и включите полезную hamcrest-библиотеку , он содержит множество полезных методов для проверки типа данных Список .

  junit junit 4.12 test  org.hamcrest hamcrest-core    org.hamcrest hamcrest-library 1.3 test   

1. Строка списка утверждений

Проверьте упаковку Проверьте упаковку , он содержит множество полезных методов для тестирования коллекции или

package com.mkyong; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.hamcrest.collection.IsEmptyCollection; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.hamcrest.MatcherAssert.assertThat; public class ListTest < @Test public void testAssertList() < Listactual = Arrays.asList("a", "b", "c"); List expected = Arrays.asList("a", "b", "c"); //All passed / true //1. Test equal. assertThat(actual, is(expected)); //2. If List has this value? assertThat(actual, hasItems("b")); //3. Check List Size assertThat(actual, hasSize(3)); assertThat(actual.size(), is(3)); //4. List order // Ensure Correct order assertThat(actual, contains("a", "b", "c")); // Can be any order assertThat(actual, containsInAnyOrder("c", "b", "a")); //5. check empty list assertThat(actual, not(IsEmptyCollection.empty())); assertThat(new ArrayList<>(), IsEmptyCollection.empty()); > > 

2. Целое число списка утверждений

Проверьте упаковку org.hamcrest.number , у него есть методы для утверждения чисел.

package com.mkyong; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.hamcrest.collection.IsEmptyCollection; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.hamcrest.MatcherAssert.assertThat; public class ListTest < @Test public void testAssertList() < Listactual = Arrays.asList(1, 2, 3, 4, 5); List expected = Arrays.asList(1, 2, 3, 4, 5); //All passed / true //1. Test equal. assertThat(actual, is(expected)); //2. Check List has this value assertThat(actual, hasItems(2)); //3. Check List Size assertThat(actual, hasSize(4)); assertThat(actual.size(), is(5)); //4. List order // Ensure Correct order assertThat(actual, contains(1, 2, 3, 4, 5)); // Can be any order assertThat(actual, containsInAnyOrder(5, 4, 3, 2, 1)); //5. check empty list assertThat(actual, not(IsEmptyCollection.empty())); assertThat(new ArrayList<>(), IsEmptyCollection.empty()); //6. Test numeric comparisons assertThat(actual, everyItem(greaterThanOrEqualTo(1))); assertThat(actual, everyItem(lessThan(10))); > > 

3. Утверждать объекты списка

package com.mkyong; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.Objects; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.junit.Assert.assertThat; public class ListTest < @Test public void testAssertList() < Listlist = Arrays.asList( new Fruit("Banana", 99), new Fruit("Apple", 20) ); //Test equals assertThat(list, hasItems( new Fruit("Banana", 99), new Fruit("Apple", 20) )); assertThat(list, containsInAnyOrder( new Fruit("Apple", 20), new Fruit("Banana", 99) )); //Test class property, and its value assertThat(list, containsInAnyOrder( hasProperty("name", is("Apple")), hasProperty("name", is("Banana")) )); > public class Fruit < public Fruit(String name, int qty) < this.name = name; this.qty = qty; >private String name; private int qty; public int getQty() < return qty; >public void setQty(int qty) < this.qty = qty; >public String getName() < return name; >public void setName(String name) < this.name = name; >//Test equal, override equals() and hashCode() @Override public boolean equals(Object o) < if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Fruit fruit = (Fruit) o; return qty == fruit.qty && Objects.equals(name, fruit.name); >@Override public int hashCode() < return Objects.hash(name, qty); >> > 

Поделитесь своим списком примеров тестирования ниже 🙂

Рекомендации

Источник

Оцените статью