Reputation: 580
When I create my unit tests, I use to declare and initialize a lot of sample shared objects used by the tests in one abstract class, extended by the classes with the tests.
E.g. I define the Product "phone" in the abstract class and I initialize it in a method called "init", annotated with @Before. I create the method @Test "savePhoneTest" in a child class which invokes the method "savePhone" using "phone". This object is always re-initialized and I can use it in other tests.
Is it possibile to store the sample objects in a XML / YML file? Is it a good practise? How can I retrieve the objects? I use spring boot. Thank you
Upvotes: 0
Views: 241
Reputation: 1829
Yes, you can use XML/YAML/JSON
to store sample objects. It will help you to write lesser code for creating sample objects. Also by using this approach your test cases will become more maintainable.
I will prefer JSON
over XML/YAML
.
Suppose you have a Product
class as shown below,
Product.java
@Data
@NoArgsConstructor
public class Product {
private int id;
private String name;
private float price;
private String brand;
}
You can create JSON file
to store objects. The JSON file
for Product
class will look like:
product.json
{
"id": 1000,
"name": "Smart phone",
"price": 60000.0,
"brand": "SAMSUNG"
}
Whenever you need any object of Product
class you can create that object using JSON file
. Below example shows how to create java object from JSON file
:
InputStream inputStream = Product.class.getResourceAsStream("/product.json");
Product product = new ObjectMapper().readValue(inputStream, Product.class);
Upvotes: 1