
Some of our test data needs to be transformed from its original type to something else. For example, we might need to convert a String to a numeric value, or vice versa. Or we might need to generate date values in a certain format. Examples for all of these can be found below.
String to int
The code
Integer.parseInt(theString)
Assign to variable of type
int
Example
int resultingInt = Integer.parseInt("6");
Value stored in the variable
6
Int to String
The code
String.valueOf(theInt)
Assign to variable of type
String
Example
String resultingString = String.valueOf(200);
Value stored in the variable
200
String to Double
The code
Double.parseDouble(theString)
Assign to variable of type
String
Example
double resultingDouble = Double.parseDouble("333.55");
Value stored in variable
333.55
Double to String
The code
String.valueOf(theDouble)
Store to variable of type
String
Example
String resultingString = String.valueOf(333.55);
Value stored in variable
333.55
Note: String.valueOf() can also be used to convert float and long values to String. Similarly, to convert String values to float you can use Float.parseFloat(), or Long.parseLong() to convert String values to long.
Time/date formatting
When working with Dates, we usually want to convert a Date value to a specific format. This can be done in Java 8 and above using DateTimeFormatter.
For example, we might want to generate the current date and time, but in the format "yyyy-MM-dd HH:mm:ss", and to save this value to a String variable. That is year-month-day hour(in 24 hours format)-minutes-seconds. To generate the current time, several approaches can be used. The first one exemplified below uses 'LocalDateTime.now()'.
To use Java's LocalDateTime and DateTimeFormatter in a test, we need to add the following imports to the test class:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
The code used for generating the date and time in the desired format as String is:
String formattedDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
The resulting String looks like:
2019-11-05 20:22:47
In case we are only interested in the year, month and day, we can omit the hour/minute/second part of the pattern used with DateTimeFormatter, as follows:
String formattedWithoutHour = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
In this case the result looks like:
2019-10-21