Java

Switch Windows Using Selenium WebDriver

Some web applications open a new window in order to section specific data entry or view.

Selenium can switch windows via the window handle.

The following is an example and must be configured for a specific website under test.

// Store the current window handle
String winHandleBefore = driver.getWindowHandle();

// Perform the click operation that opens new window
driver.findElement(By.LinkText("Open in New Window"));

// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

// Perform the actions on new window
// Do something here...

// Close the new window, if that window no more required
driver.

Get Entity Field Values as String in Java

The following uses the Apache Commons Lang library that provides the ReflectionToStringBuilder class to assist in the construction of object field values into a single String value.

This is quite useful for the viewing all the objects field values and assignments in an easily readable format.

The below example uses JDK 1.8 and the Apache Commons Lang3 library.

A book object is created and the toString() method is invoked.

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class Book {
	public String title = "";
	public String author = "";
	public String isbn

JUnit Theory Tests

A Theory JUnit test is a subset of the Parameterized JUnit test feature.

It is very similar in respects to driving tests with a set of test data, except with a few differences as explained below.

  • The test class is annotated with @RunWith(Theories.class)
  • The test does not require a constructor to assign values, which reduces the code length.
  • @DataPoint and @DataPoints annotations are used to indicate that a public static variable as a source of test data.
  • @DataPoint is a single test data value same as @Parameter
  • @DataPoints is a set of test data (iterable object) same as

Map Two Collections Together in Java

There are times where two separate entity object collections need to be mapped one-to-one.

The following code will combine two generic type collections together.

It also assesses the size of both collections and key uniqueness.

/**
 * Combines two generic type lists into a map.
 *
 * Detects key collisions and duplicate keys.
 *
 * @param keys a collection of objects
 * @param values another collection of objects the same size
 * as the key collection.
 * @return the combined map
 */
public static <K, V> Map<K, V> createMapFromCollections(  
        Collection<K> keys, Collection<V> values) {  

    Map<K, V> map