在Mockito中模拟使用ContextLoader.getCurrentWebApplicationContext调用我该怎么做?

问题描述

我尝试在使用Mockito时模拟ContextLoader.getCurrentWebApplicationContext()调用,但模拟失败。

  //here is my source code            
  @Mock
  org.springframework.web.context.WebApplicationContext webApplicationContext;

//test Case Body
 try (MockedStatic<ContextLoader> dummy = Mockito.mockStatic(ContextLoader.class)) {
                    
AnswerInfo answerInfo = Mockito.mock(AnswerInfo.class);
                    
TranDescScoreInfo descScoreInfo2 = Mockito.mock(TranDescScoreInfo.class);
                    
when(ctx.getBean("answerInfo")).thenReturn(answerInfo);
when(ctx.getBean("tranDescScoreInfo")).thenReturn(descScoreInfo2);
                    
dummy.when(() -> ContextLoader.getCurrentWebApplicationContext()).thenReturn(webApplicationContext);
                    
//ContextLoader.getCurrentWebApplicationContext() getting null I dont why it getting null.
                            
        }

//Below Code is my business logic  
 ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
 AnswerInfo answerInfo = (AnswerInfo) ctx.getBean("answerInfo");
 tranDescScoreInfo = (TranDescScoreInfo) ctx.getBean("tranDescScoreInfo");

// ctx.getBean获得空值,因为我没有按预期在此处进行模拟调用 注意:我不想更改我的业务逻辑

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)