本文介绍了在Mockito中模拟何时使用ContextLoader.getCurrentWebApplicationContext()调用.我该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试在使用Mockito时模拟ContextLoader.getCurrentWebApplicationContext()调用,但模拟失败.
I am trying to mock ContextLoader.getCurrentWebApplicationContext() call in when using mockito but its fails to mock.
//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获得空值,因为我没有按预期在此处进行模拟调用注意:我不想更改我的业务逻辑
// ctx.getBean getting null because i am not getting mock call here as expectedNote: I don't want to change my business logic
推荐答案
您必须在尝试中移动代码.我希望这对您有用:
You have to move the code inside the try. I hope this works for you:
class UserTest {
@Mock
WebApplicationContext webApplicationContext;
@BeforeEach
void setUp() throws Exception {
MockitoAnnotations.openMocks(this);
}
@Test
void test() {
//test Case Body
try (MockedStatic<ContextLoader> dummy = Mockito.mockStatic(ContextLoader.class)) {
Mockito.when(webApplicationContext.getBean("answerInfo")).thenReturn(new String());
dummy.when(ContextLoader::getCurrentWebApplicationContext).thenReturn(webApplicationContext);
//Below Code is my business logic
ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
assertNotNull( ctx.getBean("answerInfo"));
}
}
}
这篇关于在Mockito中模拟何时使用ContextLoader.getCurrentWebApplicationContext()调用.我该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!