Test Observability & Engineering effectiveness
“Engineering Effectiveness” has been a central topic of discussion and focus this year
Testing across all interfaces, platforms and architectural components
Product test engineering, Shift-Left testing and digital transformation
Automate tests across all interfaces, platforms and horizontal scaling
Generative AI, Flutter, React Native, Micro-services, Micro-frontends & TestOps
Measure and enhance the efficiency & effectiveness of testing teams & solutions
Offshore Testing Setup as a Service, platform engineering and Modernisation
How to Read YAML File in Java using YamlBean
This blog covers how to read YAML files by using the YamlBeans library. Before going to the library let us know the basic details of YAML.
YAML stands for YAML Ain’t Markup Language.
YamlBeans is a free library where it makes easy to serialize and deserialize Java object graphs to and from YAML, a human-friendly data format. Replace XML and properties files with YAML for more expressive power (lists, maps, anchors, etc) and easier hand-editing.
YamlBean as Gradle dependency:
// https://mvnrepository.com/artifact/com.esotericsoftware.yamlbeans/yamlbeans
implementation 'com.esotericsoftware.yamlbeans:yamlbeans:1.15'
The YamlReader class is used to deserialize YAML to Java objects.
Let’s consider we have placed the Yaml file in resources and need to read the following YAML defines a Map with six entries.
id: '1'
name: name1
phoneNumbers:
- phoneNumber1
- phoneNumber2
salary: 1000
status: NEW
age: 35
Now we need to validate the salary by reading the Yaml. This can be achieved by following steps.
Step 1: Get the file in the project
public File getFile(String path) {
return new File(YamlBeansFileReader.class.getClassLoader().getResource(path).getFile());
}
Step 2: Use YamlReader to reads the YAML document and deserialize it into HashMaps, ArrayLists, and Strings. Since we know the root object defined in the YAML of our example is a Map, we can cast the object and use it.
public Object readAsObject(File filePath, String value) throws FileNotFoundException, YamlException {
YamlReader yamlReader = new YamlReader(new FileReader(filePath));
Map read = (Map) yamlReader.read();
return read.get(value);
}
Step 3: Validate the data.
@Test
public void readAsMap() throws YamlException, FileNotFoundException {
File file = resourceFileReader.getFile("data/employee.yml");
Object salary = new YamlBeansFileReader().readAsObject(file, "salary");
System.out.println(salary);
Assert.assertTrue(salary.equals("1000"));
}
Deserializing other classes
There are two ways to deserialize something other than HashMaps, ArrayLists, and Strings.
Step 1: Java class for same YAML document:
package com.testvagrant.yamlreader.tests.models;
import java.util.List;
public class Employee {
private String id;
private String name;
private String status;
private float salary;
private List phoneNumbers;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public List getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.id).append(",");
sb.append(this.name).append(",");
sb.append(this.status).append(",");
sb.append(this.salary);
sb.append(this.age);
return sb.toString();
}
}
Step 2: The “read” method can be passed a class, so the YamlReader knows what it is deserializing:
public File getFile(String path) {
return new File(YamlBeansFileReader.class.getClassLoader().getResource(path).getFile());
}
public T read(File filePath, Class tClass) throws FileNotFoundException, YamlException {
YamlReader yamlReader = new YamlReader(new FileReader(filePath));
T obj = yamlReader.read(tClass);
return obj;
}
Step 3: Validate the data
@Test
public void readAsAnObject() throws YamlException, FileNotFoundException {
File file = resourceFileReader.getFile("data/employee.yml");
Employee employee = new YamlBeansFileReader().read(file, Employee.class);
Assert.assertEquals(employee.getId(), "1");
Assert.assertEquals(employee.getAge(), 35);
}
The YamlReader creates an instance of the Employee class and sets the “id” and “age” fields. The YamlReader determines the “age” value in the YAML needs to be converted into an int. Deserialization would have failed if the age was not a valid int. The YamlReader can set public fields and bean setter methods.
YamlReader for nested data in YAML document specified in the YAML using a tag.
name: field3
type: short
length: 2
comment: Error
variableFields:
- !com.testvagrant.yamlreader.tests.models.VariableField
id: 1
name: nestedField 1
type: Long
length: 3
comment:
---
Step 1: Java class for same YAML document:
package com.testvagrant.yamlreader.tests.models;
import java.util.List;
public class MessageField {
public String name;
public String type;
public int length;
public String comment;
public List variableFields;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public List getVariableFields() {
return variableFields;
}
public void setVariableFields(List variableFields) {
this.variableFields = variableFields;
}
}
package com.testvagrant.yamlreader.tests.models;
public class VariableField {
public int id;
public String name;
public String type;
public int length;
public String comment;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
Step 2: The “read” method can be passed a class, so the YamlReader knows what it is deserializing:
public File getFile(String path) {
return new File(YamlBeansFileReader.class.getClassLoader().getResource(path).getFile());
}
public T read(File filePath, Class tClass) throws FileNotFoundException, YamlException {
YamlReader yamlReader = new YamlReader(new FileReader(filePath));
T obj = yamlReader.read(tClass);
return obj;
}
Step 3: Validate the data
@Test
public void readByNestedDetails() throws YamlException, FileNotFoundException {
File file = resourceFileReader.getFile("data/variablefield.yml");
MessageField field = new YamlBeansFileReader().read(file, MessageField.class);
Assert.assertTrue(field.getVariableFields().stream()
.anyMatch(variableField -> variableField.getName().equals("nestedField 1")));
}
}
Yes, in addition to Yambean, another SnakeYAML Engine, a SnakeYAML reader is available to read YAML documents.
Yamlbeans is a Java library commonly used in utilities and applications that handle YAML. YamlBeans makes it easy to serialize and decode Java object graphs to and from YAML, a user-friendly data format. Replace XML files and properties with YAML for more expressive power (lists, maps, anchors, etc) and easier manual editing.
Share This Article
“Engineering Effectiveness” has been a central topic of discussion and focus this year
With us, you’re not just a part of a company; you’re part of a movement dedicated to pushing boundaries, breaking barriers, and achieving the extraordinary.
Otaku 2.0 sought to redefine the way we approach testing, celebrate the spirit of innovation, and pave the way for a brighter future in tech.