【问题标题】:Mocking passed functional interfaces in spring + Mockito在 spring + Mockito 中模拟传递的功能接口
【发布时间】:2021-10-18 00:11:24
【问题描述】:

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

 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-testing mockito spring-boot-test


    【解决方案1】:

    使用 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);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      相关资源
      最近更新 更多