[英]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()
方法中的行,但由於以下原因沒有成功
java.lang.NoSuchMethodException:
你能給我一個解決方案來覆蓋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.