Issue
I am creating couple of unit tests for testing my application logic. In the below, I have created two final variables based on whether order is true or not. Is there a way to make it DRY by not having to create a final variable for each and every order type?
private static final Order FIRST_ORDER = createOrder(
"watch",
"123",
true
);
private static final Order SECOND_ORDER = createOrder(
"watch",
"123",
false
);
private static Order createOrder(String productName, String productId, Boolean isNewOrder){
//Logic
}
@Test
public void shouldTestOrderCreation(){
OrderHelper helper = new OrderHelper();
helper.createOrder(FIRST_ORDER);
}
@Test
public void shouldTestOrderCreation(){
OrderHelper helper = new OrderHelper();
helper.createOrder(SECOND_ORDER);
}
Solution
What's wrong with this?
@Test
public void testNewOrder(){
createOrder(true);
}
@Test
public void testNotNewOrder(){
createOrder(false);
}
void createOrder(boolean newOrder) {
OrderHelper helper = new OrderHelper();
helper.createOrder("watch", "123", newOrder);
}
You can also parameterize tests:
@ParameterizedTest
@ValueSource(booleans={true, false})
void createOrder(boolean newOrder) {
OrderHelper helper = new OrderHelper();
helper.createOrder("watch", "123", newOrder);
}
But it all depends on what kind of assertions you want to test.
Answered By - Davide D'Alto
Answer Checked By - Mildred Charles (JavaFixing Admin)