简体   繁体   中英

Creating DRY Junit test objects

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM