簡體   English   中英

匿名class返回TestNG時如何測試私有方法

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

我需要使用 TestNG 測試 StockPrice class 中的getPrice()方法,並覆蓋priceCalculator()方法中的行

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

我嘗試以多種方式覆蓋 1 priceCalculator()方法中的行,但由於以下原因沒有成功

  • getStock() 方法是私有方法,因此無法訪問它。 我嘗試使用反射來訪問它,但得到了java.lang.NoSuchMethodException:
  • getStock() 返回 Annonymous object。然后不能覆蓋 priceCalculator() 方法的行

你能給我一個解決方案來覆蓋priceCalculator方法中的行嗎?

總之,我需要涵蓋以下代碼。

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

通過公共方法測試它。

Stock class 不訪問任何外部和緩慢的資源,所以你不需要模擬任何東西。

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

    double actual = stockPrice.getPrice();

    assertEquals(800, actual);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM