Mockito – `doCallRealMethod`在Spring Boot应用中不按预期工作

huangapple 未分类评论51阅读模式
英文:

Mockito - doCallRealMethod not working as expected in springboot application

问题

在 Mockito 中doCallRealMethod 方法对于带有字符串参数的方法在我的情况下无法按预期工作即其被模拟而不是调用实际方法)。

我有以下类

类 A
    
    @Autowired
    Utils utils;

    public void invokerMethod(String a, String b, String c) {
        utils.realMethod(a, b, c);
        // ...
        // ...
    }

类 Utils
    
    public class Utils throws Exception {
        public void realMethod(String a, String b, String c) {
            if (a.equals("")) {
                throw someException();
            }
        }
    }

类 ATest

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class ATest() {
        @Autowired
        A a;

        @MockBean
        Utils utils;

        @Test
        public void invokerMethodTest() {
            doCallRealMethod().when(utils).realMethod(anyString(), anyString(), anyString());
            a.invokerMethod("", "", "");
        }
    }

我尝试将 anyString 替换为 ""new String()但对我来说仍然无法正常工作

注意:上述翻译中可能存在一些技术术语或代码标记,因此在实际使用时,您可能需要根据上下文进行微调。如果您需要进一步的帮助,请随时告知。

英文:

doCallRealMethod in mockito is not working as expected for me(i.e its getting mocked instead of calling real method) for method having string arguments.
I have following classes

Class A{
  @Autowired
  Utils utils;


  public invokerMethod(String a,String b,String c){
      utils.realMethod(a,b,c);
      .....
      ......   

 }
}

Class Utils:

Class Utils throws Exception{
        public void realMethod(String a,String b,String c)     
             if(a.equals(""))
                 throw someException();
   }

Class ATest:

@RunWith(SpringRunner.class)
@SpringBootTest
Class ATest(){
    @Autowired
    A a;

   @MockBean
   Utils utils;

   @Test
public invokerMethodTest(){
doCallRealMethod().when(utils).realMethod(anyString(),anyString(),anyString());
      a.invokerMethod("","","");
 }
}

I tried replacing anyString with "", new String() but still its not working for me

huangapple
  • 本文由 发表于 2020年4月10日 20:28:17
  • 转载请务必保留本文链接:https://java.coder-hub.com/61140250.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定