我有这个服务类 -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。当处理的某些部分委托给另一个类时,它特别有用,但这里不是这种情况。
皈依舞
TA贡献1851条经验 获得超3个赞
创建一个对象FeeCalcService
并调用init()
with 对象。然后calculateFee
使用相同的对象调用 ,然后使用具有预期值的实际值进行验证。
添加回答
举报
0/150
提交
取消