【问题标题】:How to test init function with @Postconstruct and map inside with junit mockito如何使用 @Postconstruct 测试 init 函数并使用 junit mockito 在内部进行映射
【发布时间】:2022-01-20 08:58:26
【问题描述】:

我有一门课要测试,但我不知道如何测试它。有人可以帮忙测试吗?

@Component
public class KvkkCorrBankingExecuter {

    private final Map<String, IKvkkCorrBankingExecuter> operationMap = new HashMap<>();

    IKvkkCorrBankingExecuter executer;

    @Autowired
    DemandBoeExecuter demandBoeExecuter;

    @Autowired
    DemandCleanBaExecuter demandCleanBaExecuter;

    @Autowired
    DemandGuaranteeExecuter demandGuaranteeExecuter;

    @Autowired
    DemandLcExecuter demandLcExecuter;

    @Autowired
    DemandSlcExecuter demandSlcExecuter;

    @PostConstruct
    public void init() {
        operationMap.put("DEMAND_BOE", demandBoeExecuter);
        operationMap.put("DEMAND_CLEAN_BA", demandCleanBaExecuter);
        operationMap.put("DEMAND_GUARANTEE", demandGuaranteeExecuter);
        operationMap.put("DEMAND_LC", demandLcExecuter);
        operationMap.put("DEMAND_SLC", demandSlcExecuter);
    }
}

映射线和初始化函数在协变中以红色突出显示。它们需要进行测试。

【问题讨论】:

    标签: java testing junit hashmap mockito


    【解决方案1】:

    我不会给出现成的答案,而是一些指导。我建议您尝试一下,这是学习和记住的唯一方法。

    如何为这个类编写单元测试? 单元测试的目标是测试所有可能的场景。目标不应只是使代码覆盖率报告变为红色,而应避免该代码在各种数据条件下出现任何可能的错误。

    由于您是通过 jUnit 进行测试,请执行以下操作:

    1. 创建一个测试类 - 给出类名,以便它指示正在测试的类。例如KvkkCorrBankingExecuterTest.java
    2. 编写一个方法,其名称说明您正在测试什么条件。 例如testInitFunction()
    3. 由于您没有使用 spring 进行测试,@Postconstruct 注解的方法不会被自动调用。

    由于测试没有使用spring,自动装配的属性将为空。 为此,请创建与正在测试的类具有完全相同定义的 Mock 变量。

    然后执行以下操作:

    Class KvkkCorrBankingExecuterTest{
    //other mock variables similar to demandLcExecuter
    
    @Mock 
    DemandLcExecuter demandLcExecuter;
      
    @Before
    public void init(){
      MockitoAnnotations.initMocks(this);
    }
    
    @Test
    public void testInitMethod(){
     //  1. Create an instance of KvkkCorrBankingExecuter 
     // 2. Call init() method on that instance
     // 3. Validate that the size of operationMap is 5
     // 4. Validate that you get values corresponding to each key. The value will be // equal to the mock attributes in this class.
       
    }
    
    }
    

    其他代码建议: 将属性设为私有。

    【讨论】:

    • 问题是当我调用 init 函数时我无法获取 operationMap。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多