简体   繁体   中英

How to test a private method when anonymous class return in TestNG

I need to test getPrice() method in StockPrice class by using TestNG. and cover the lines inside the priceCalculator() method

public class StockPrice {

  public double getPrice(){
    Stock stock = getStock();
    return finalPrice(stock,1000,true);
  }

  private double finalPrice(Stock stock, int price, boolean isDiscountAvailable){
    return stock.priceCalculator(price,isDiscountAvailable)-100;
  }

  private Stock getStock(){
    return new Stock()
    {
      @Override
      public double priceCalculator(int price, boolean isDiscountAvailable)
      {
        if (isDiscountAvailable){
          return price-price/10;
        }else {
          return price;
        }
      }
    };
  }
}

interface Stock{
  double priceCalculator(int price, boolean isDiscountAvailable);
}

I tried to cover the lines inside the 1 priceCalculator() method in several ways but did not succeed due to the following reasons

  • getStock() method is a private method so cannot access it. I tried with using reflections to access it but got java.lang.NoSuchMethodException:
  • getStock() returns and Annonymous object. Then cannot cover the lines priceCalculator() method

can you give me a solution to cover the lines in the priceCalculator method.

in summary, I need to cover the following code.

@Override
public double priceCalculator(int price, boolean isDiscountAvailable)
{
  if (isDiscountAvailable){
    return price-price/10;
  }else {
    return price;
  }
}

Test it through public method.

Stock class doesn't access any external and slow resources, so you need to mock nothing.

@Test
public void getPrice_returns_expected_price() {
    StockPrice stockPrice = new StockPrice();

    double actual = stockPrice.getPrice();

    assertEquals(800, actual);
}

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