亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Junit / Mockito 為這個費用計算器服務編寫測試用例?

如何使用 Junit / Mockito 為這個費用計算器服務編寫測試用例?

慕的地6264312 2021-10-13 17:23:40
我有這個服務類 -package com.test.common.fee;import java.io.File;import java.io.IOException;import java.math.BigDecimal;import java.math.MathContext;import javax.annotation.PostConstruct;import org.codehaus.jackson.map.ObjectMapper;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;@Servicepublic class FeeCalcService {    @Value("${json.config.folder}")    String jsonConfigFolder;    FeeConfigEntity feeConfig = new FeeConfigEntity();    @PostConstruct    public void init() throws IOException {        ObjectMapper jsonMapper = new ObjectMapper();        File jsonFile = getFilesInFolder(jsonConfigFolder);        // deserialize contents of each file into an object of type        feeConfig = jsonMapper.readValue(jsonFile, FeeConfigEntity.class);    }    public BigDecimal calculateFee(BigDecimal amount)    {        String type = feeConfig.getType();        Integer total = feeConfig.getDetails().size();        BigDecimal fee = new BigDecimal(0);        if(type.equals("slab"))        {            if(total>1)            {                for(FeeConfigDetailsEntity eachSlab : feeConfig.getDetails()){                    BigDecimal min = BigDecimal.valueOf(eachSlab.getDetails().getMin());                    BigDecimal max = BigDecimal.valueOf(eachSlab.getDetails().getMax());                    if((amount.compareTo(min) == 1 || amount.compareTo(min) == 0)                            &&                        (amount.compareTo(max) == -1 || amount.compareTo(min) == 0)                    )基本上,這是一項服務,根據 json 文件中定義的傭金結構,返回輸出的傭金/費用將適用于某個金額。這就是我從我的應用程序中調用它的方式 -BigDecimal fee = feeCalcService.calculateFee(amount);我對 Junit 測試很陌生,我不知道應該如何做到這一點。我的想法是——服務類結構需要進行一些更改。init 函數不返回任何東西,所以我不能在這里放一個 when() thenReturn() ,否則我可以用我需要的東西在這里覆蓋。  
查看完整描述

2 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

在我看來,FeeCalcService應該針對幾個不同的FeeConfigEntity實體進行測試。


有不同的方法可以實現,例如:


將 2 個構造函數添加到您的類中:


public FeeCalcService() {

}


FeeCalcService(FeeConfigEntity feeConfig) {

    this.feeConfig = feeConfig;

}

第二個僅用于測試。


然后像這樣寫一些測試:


@Test

public void test1() {

    FeeConfigEntity config1 = new FeeConfigEntity();

    config1.setType(...);

    config1.setDetails(...);

    Assert.assertEquals(new BigDecimal(10), new FeeCalcService(config1).calculateFee(new BigDecimal(100)));

}

這里不需要 Mockito。當處理的某些部分委托給另一個類時,它特別有用,但這里不是這種情況。


查看完整回答
反對 回復 2021-10-13
?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

創建一個對象FeeCalcService 并調用init()with 對象。然后calculateFee使用相同的對象調用 ,然后使用具有預期值的實際值進行驗證。


查看完整回答
反對 回復 2021-10-13
  • 2 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號