首页 > 解决方案 > 在 spring + Mockito 中模拟传递的功能接口

问题描述

我正在为作为行为传递的方法创建测试,我不确定模拟如何用于功能性。我不想模拟executeBehaviour调用,而是模拟行为 function.apply 的实际执行

 public String processData(){
        String a="check";
        return executeBehaviour((check)->"hello"+check,a);
    }
 public  String executeBehaviour(Function<String,String> data,String data1){
        //Some processing
            return data.apply(data1);
    }

我已经编写了以下测试用例,但它似乎没有模拟 data.apply() 调用。测试用例:

  @Test
    void sampleTest() {
        Function<String, String> processFunction = mock(Function.class);
        String test = "check";
        when(groupingFunction.apply(anyString())).thenReturn(test);
        String data = itemInventoryProcessorService.executeBehaviour(processFunction,test);
        Assertions.assertEquals("check", data);
    }

断言失败,因为写入的数据是实际执行的行为,即“hellocheck”而不是模拟的“check”。

标签: unit-testingmockitospring-boot-test

解决方案


使用 doAnswer,我们可以提供函数的实现并返回我们正在尝试验证的假/存根结果。通过这种方式,我们基本上是自己为函数提供了一个存根。

 @Test
    void sampleTest() {
        String test = "check";
        doAnswer(invocation -> {
            Function<String, String> processingFunction = invocation.getArgument(0);
            groupingFunction.apply("dummy");
            return test;
        }).when(itemInventoryProcessorService). executeBehaviour(any(Function.class), anyString());
        var data = itemInventoryProcessorService. processData();
        Assertions.assertEquals("check", data);
    }

推荐阅读