Home > OS >  Creating DRY Junit test objects
Creating DRY Junit test objects

Time:07-27

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);
  }

CodePudding user response:

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.

CodePudding user response:

Function calls instead of constants are better; the have the same life cycle/time as a single unit test method. A data constructing function is not bad. I think that is the most stylistic irritation one feels on constants.

This holds even for complex data with references to other data. I might even be argued that having the data locally together is more readable.

In both cases DRY probably means not to have probably irrelevant properties copied with same values, like product names. But that is to some degree unavoidable.

  • Related