英文:
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
专注分享java语言的经验与见解,让所有开发者获益!



评论