如何编写JUNIT测试案例,用于具有多个可呼叫的执行器服务



因此,在我的服务层中,我有一种公开方法调用一种私人方法(在junit中涵盖的方法(,进而将其他私人方法调用以进行某些计算。我需要为此方法编写junit。

嘲笑可可无济于事

private void Method1(Long num, Map<String,Object> result){
    ExecutorService es = Executors.newFixedhreadPool(3);
    List<Callable<SomeVo> callables = Array.asList(
        getCallable(this::method1,num),
        getCallable(this::method2,num),
        getCallable(this.method3,num));
    try{
        List<Future<SomeVo> futures = es.involeAll();
        executor.shutdown();
        for(Future<Somevo> f : futures){
            somemethod(f,result);
        }
    } catch (InteruptedException e) { }
private SomeVo method1(Long num){
    return someVo; 
}
private void somemethod(Future<SomeVo> f ,Map<String,Object> res){
    result.put("key", f.get());
}

简单地重构您的代码,将Method1提取到某种接口/抽象类,然后提供callables的列表作为方法参数(只需使用依赖项注入/em>模式(。然后,在您的公共方法中,您可以使用一些私有实现来进行接口。

这样,您可以提供一组模拟/测试实现,并查看它们是否被称为

我的意思是在划痕中(将此代码视为伪代码示例,您应该专注于在此处进行重构以正确地进行重构(是

public abstract class ResultProcessor {
    public void processResults(Long num, Map<String,Object> result, List<Callable<SomeVo> callables){
        // ...
    }
}
// then in the class of your public method create private implementation
...
public void yourPublicMethod() {
    // instead of calling Method1(num, result)
    new Method1Processor().processResults(num, result);
}
private static class Method1Processor extends ResultProcessor {
    public void processResults(Long num, Map<String,Object> result, List<Callable<SomeVo> callables){
        List<Callable<SomeVo> callables = Array.asList(
                 getCallable(this::method1,num),
                 getCallable(this::method2,num),
                 getCallable(this.method3,num));
        super.processResults(num, result, callables);
    }
    private SomeVo method1(Long num){
        return someVo; // yes you still have access to fields of parent class :)
    }
    private void somemethod(Future<SomeVo> f ,Map<String,Object> res){
        result.put("key", f.get()); // here is the same
    }
}

现在,您可以轻松地提供自己的实现来测试ResultProcessor Logic

最新更新