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

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

Mockito - doCallRealMethod not working as expected in springboot application

问题

  1. Mockito doCallRealMethod 方法对于带有字符串参数的方法在我的情况下无法按预期工作即其被模拟而不是调用实际方法)。
  2. 我有以下类
  3. A
  4. @Autowired
  5. Utils utils;
  6. public void invokerMethod(String a, String b, String c) {
  7. utils.realMethod(a, b, c);
  8. // ...
  9. // ...
  10. }
  11. Utils
  12. public class Utils throws Exception {
  13. public void realMethod(String a, String b, String c) {
  14. if (a.equals("")) {
  15. throw someException();
  16. }
  17. }
  18. }
  19. ATest
  20. @RunWith(SpringRunner.class)
  21. @SpringBootTest
  22. public class ATest() {
  23. @Autowired
  24. A a;
  25. @MockBean
  26. Utils utils;
  27. @Test
  28. public void invokerMethodTest() {
  29. doCallRealMethod().when(utils).realMethod(anyString(), anyString(), anyString());
  30. a.invokerMethod("", "", "");
  31. }
  32. }
  33. 我尝试将 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

  1. Class A{
  2. @Autowired
  3. Utils utils;
  4. public invokerMethod(String a,String b,String c){
  5. utils.realMethod(a,b,c);
  6. .....
  7. ......
  8. }
  9. }

Class Utils:

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

Class ATest:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. Class ATest(){
  4. @Autowired
  5. A a;
  6. @MockBean
  7. Utils utils;
  8. @Test
  9. public invokerMethodTest(){
  10. doCallRealMethod().when(utils).realMethod(anyString(),anyString(),anyString());
  11. a.invokerMethod("","","");
  12. }
  13. }

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:

确定